0

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.

2
  • I am trying to return the groups with same id. mean? Commented May 18, 2017 at 12:41
  • Trying to run products that belong to a group. So the product array. Should be products with the same camapign_id. Commented May 18, 2017 at 12:50

5 Answers 5

2

A simple inner join should suffice here, right?

$groups = \App\Group::join('product', 'group.campaign_id', '=', 'product.group')
                    ->where('group.campaign_id', $id)
                    ->get();
Sign up to request clarification or add additional context in comments.

Comments

2

try :

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

Comments

1

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 :)

Comments

1

I'm not sure but you may try this:

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

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.