1

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();
berndpeter
  • 57
  • 7
  • Can you include a little more information about your database schema, model relationships, and the expected result? – Travis Britz Mar 05 '19 at 08:36
  • Database schema: --RoomProduct || select product_id, value ---Products (product_detail) || select title ----Category the query above is working fine and i get the product_id and the sum of value but i cant get any fields from nested table "product_detail" I need this output: * Category_id ** Product_id, Total, Title (product_detail) – berndpeter Mar 05 '19 at 08:59
  • 1
    Because whereHas method is use only for apply condition on database.You need to use `with('product_detail')` method with `whereHas("product_detail")` method. – paresh kalsariya Mar 05 '19 at 13:23

1 Answers1

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.