问题
I am trying to select columns (id, title) of the relationship database (product_detail) but it's not working at all.
My Query:
RoomProduct::select('product_id', DB::raw('SUM(value) as total'))
->whereHas('room.offer', function($sql) use ($offer_id) {
$sql->where('id', $offer_id);
})->whereHas('product_detail', function($sql) use ($category_id) {
$sql->select("id", "title")->with(['category' => function ($query) {
$query->where('parent_id', $category_id);
}])->orWhere('id', $category_id);
})->groupBy("product_id")->get();
回答1:
First have a read of the top rated answer of this post -> Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
The whereHas()
method is the same as the has()
method except it allows you to provide additional where clauses inside of your closure. But both of these methods only return models that have the relationship you have asked for. This does not mean it will return any columns in those relationships though.
You will need to use the with()
method to obtain the columns you are looking for and then reference them in your select as something like select('product_id', DB::raw('SUM(value) as total'), 'product_detail.id', 'product_details.title')
I hope this has helped you! If it's not clear or have any questions i'll be sure to respond as quick as possible.
来源:https://stackoverflow.com/questions/54998033/collection-relationship-select-columns-not-working-laravel