Collection Relationship Select columns not working Laravel

拈花ヽ惹草 提交于 2021-01-28 05:24:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!