简体   繁体   中英

Laravel eloquent selecting colms from third table using eager loading

I have three Model User Review and Product . Product has a hasMany relation with User model. And User model has a hasOne relation with Review model.

But there is no relation between Product and Review Model. I am trying to select the products with users and want to select that user's rating from review model. Here is my code what I am trying to do..

 $product=new Product;
 $product->where('status', 1)
            ->with(array('user'=>function($query){
                $res=$query->select('id', 'userName', 'profilePic','firstName', 'lastName');
               /*$rating=Review::where('user_id',$res->id);*/ this doesn't work but may be I need something similar? 
            }))
            ->with('cocabeanconditioning')
            ->with('Image')
            ->orderBy('created_at', 'desc')
            ->paginate(9);

Thank you.

使用点表示法,例如:

->with('user', 'user.review')

You can select specific columns for relations like this:

$products = Product::with(['user'=>function($q){
            $q->select('users.id')->with(['review'=>function($q){
                $q->select('reviews.rating');
            }]);
        }])->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM