Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cooperino's avatar

What is the correct query in my case with pivot table?

I'm having hard time figuring out the query I need in my scenario. Not sure I can use eloquent alone and I might use raw query. There are the following tables: lists, items, and the pivot table items_to_lists, which has the columns list_id and items_id

Relationships are set like so - items hasMany items_to_lists and lists belongsToMany items_to_lists

I am given a list id, and I need to get all the items that belong to this list and to the user's account (which is easy to find by Auth::user()->account)

Is it possible to do using eloquent or I will need some use of raw queries? And what would be the more efficient way if there are tens of thousands of items?

Thanks

0 likes
8 replies
cooperino's avatar

@Nakov Update: My mistake again.. With all the similar names I missed it. I actually do have these relationships: Both Items and Lists have belongsToMany via the pivot table.

Does it make it possible to get the necessary query using eloquent alone? Something like Lists::where('id', $list_id)->items()?

cooperino's avatar

@Nakov I was about to write the following (using your help from the old post):

Lists::with('items')->whereIn('id', [3])->get();, as you can see I'm still not too experienced and did unnecessary whereIn as if I was passing an array. Slowly learning, thank you!

Nakov's avatar

@cooperino Just remember that ->get() will return a collection of lists in this case. So are there other lists with the same id ? I guess not.. so in such case you are looking for find(ID) method on the eloquent model. It will return single instance of the model, and ->with() is just to eager load the relation items.

1 like
cooperino's avatar

Yep, I changed it and it looks good now

But now I'm having trouble with filtering to get few columns only from the items.

I tried: Lists::with('items')->find($list_id)->items->pluck($columns...);

But the find() does not return collection of models, it returns an all array:

=> Illuminate\Database\Eloquent\Collection {#1221
     all: [
      App\Models\Items{#1241

How can I make it similar to something like Items::all() to get collection of Items models? (confusion)

Update: I made some filtering using query inside with:

$items = Lists::with(['items' => function ($query) {
        $query->select('column1', 'column2');
    }])->find(3);

Please or to participate in this conversation.