简体   繁体   中英

Laravel eloquent query with

This query returns all groups with an id however it also returns all the products to every group.

$groups = \App\Group::where('campaign_id', $id)->with('product')->get();
    dd($groups->toArray());array:2 [▼

This is the output.

0 => array:6 [▼
    "id" => 24
    "campaign_id" => "TRE36934"
    "group_name" => "group2"
    "created_at" => "2017-05-17 16:14:55"
    "updated_at" => null
    "product" => array:4 [▼
      0 => array:8 [▶]
      1 => array:8 [▶]
      2 => array:8 [▶]
      3 => array:8 [▶]

I am trying to return the groups with same id. Can I somehow query? The join in the id in the groups table and the foreign key in call 'group' in the group table.

A simple inner join should suffice here, right?

$groups = \App\Group::join('product', 'group.campaign_id', '=', 'product.group')
                    ->where('group.campaign_id', $id)
                    ->get();

try :

$groups = Group::join('product', 'group.campaign_id', '=', 'product.group')
                    ->where('group.campaign_id', $id)
                    ->get();

If you want to get your product with the same campaing id, you can do the following :

$products = Product::get()->groupBy('campaign_id');

Or you can do it directly from SQL

So, if you want a collection of Product, use your product model :)

I'm not sure but you may try this:

$group = \App\Group::where('campaign_id', $id)->get();
$group->load('products'); 

Thanks for all your replies they all got me a bit cloer

$products = \App\Product::join('groups', 'groups.id', '=', 'products.group')->get()->groupBy('group');

The basic groupby by Mathieu Ferre got me close. I added a join with a groupby as suggested by Mozammil on the name to give me

$products = \App\Product::join('groups', 'groups.id', '=', 'products.group')->get()->groupBy('group_name');

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