[英]Laravel eloquent selecting colms from third table using eager loading
I have three Model User
Review
and Product
.我有三个 Model User
Review
和Product
。 Product has a hasMany
relation with User
model. Product 与User
模型有hasMany
关系。 And User
model has a hasOne
relation with Review
model.并且User
模型与Review
模型有hasOne
关系。
But there is no relation between Product
and Review
Model.但是Product
和Review
模型之间没有关系。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.