Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 1 year ago.
0

I like your backgroud.
First, I would suggest you to change the whereHas() into a whereExists(). That would speed up your query. But none of them are good in this case.
You are accessing the pivot wrong. The pivot is accessed using the related model. You didn't load the pivot here, just take a lot of LUsers. There is no relation and no pivot to access. In your SQL you can clearly see that it doesn't return anything from the user_group_xref table.
A simple way would be to load the Club model from the DB including the related LUsers.

$clubModel = Club::with('users')->where('slug', '=', $club)->first();
foreach($clubModel->users as $user){
            $items[] = array(
                'id' => $user->id,
                'first_name' => $user->name_first,
                'last_name' => $user->name_last,
                'city' => $user->city,
                'state' => $user->state,
                'joined' => $user->pivot->date_joined
            );
}

This would work, but you still have to figure out how to limit it before loading. If you watch the query log, you will note that it makes two queries. Since there is only one match for the club model inside the database, eager loading the users is same as getting them for the matched club model.

$clubModel = Club::where('slug', '=', $club)->first();
$severalUsers = $clubModel->users()->take(20)->get();
foreach...

Maybe paginate will make your life easier.

Last updated 1 year ago.
0

Thanks for the help. I thought that original SQL was weird. Didn't know about the whereExists.

I did do the option you suggested but didn't think of the second part with ->users()->take.

I'll take a look at paginate also, which is really what I want.

The light bulb went on now with the pivot. I was confused why that wasn't working.

thank you

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

martyphee martyphee Joined 23 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.