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

resting's avatar

Question about building relationships

I have 3 tables. Users, Projects, Items. There's also a Pivot Table Project_User for the many-to-many relationship between projects and users.

So I can get projects assigned under the logged in user like: Auth::user()->projects()->get(). This is working fine.

Items belongsTo one project.

Now I'm not sure how to build the relationship so that I can retrieve the items similar to how I get the projects. Something like: Auth::user()->items()->get().

Option 1: I can get all the projects associated with the user first, then iterate everyone to get the items. I don't like this cause I think it should be possible to do it in one step?

Options 2: Somehow I can build a relationship or query in User.php to get access directly to items? This is the part I'm not sure of.

So I realise mine is a typical hasManyThrough pivot table problem. Doesn't seem like there's a good solution around.

0 likes
5 replies
bunnypro's avatar

how about

Auth::user()->projects()->with('items')->get()->map(function ($project) {
    return $project->items;
})->flatten();
1 like
bunnypro's avatar

i have a better one (laravel 5.4)

Auth::user()->projects()->with('items')->get()->flatMap->items;
resting's avatar

It kinda works, but I don't have flatMap probably because I'm at 5.2.

So now I need to pass off the query to a paginator and this is what I have:

Auth::user()->projects()->with('items')->orderBy('updated_at', 'desc')->paginate($limit)

But I think it's paginating the projects instead of items. See screenshot of dd() result: http://i.imgur.com/DsCC7be.jpg

Think I have to make items the main subject instead of `projects' somehow.

Maybe it's not possible with relationships. Probably will have to use query builder.

bunnypro's avatar
bunnypro
Best Answer
Level 7

because we are querying the projects, not the item :)

so we should do like this

Item::whereHas('project.users', function ($query) {
    $query->where('id', auth()->id());
})->orderBy('updated_at', 'desc')->paginate($limit)

*updated

resting's avatar

Wow. It actually works.

And it's better than query builder cause it returns Items objects instead of a standard object.

Nice. Thanks.

Please or to participate in this conversation.