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

Deekshith's avatar

Laravel hasmany relationship query

I have two tables User table and user membership table user membership table consists every year data for a user.

Example: User table

id name 1 Deekshith

User Membership Table:

id user_id started_at ended_at 1 1 2018-01-01 2018-12-31 2 1 2019-01-01 2019-12-31

So it has one to many relation

My question is how to fetch record from user table using laravel Eloquent: Relationships and query should return record from user membership table which has max of id.

please check my query below,

$users = User::where('role_id',2)->with(['membership' => function($query){

$query->where(DB::raw('users_membership.id  IN ( SELECT MAX(id) FROM users_membership GROUP BY users_id )'))
->select('started_at','ended_at'); //you may use any condition here or manual select operation

}])->with(['payment' => function($query){

$query->where(DB::raw('id IN ( SELECT MAX(id) FROM user_payment_details GROUP BY user_id )')) ->select('amount','status'); //you may use any condition here or manual select operation

}])->select('users.email')->get();

But above query returns cardinally violation on mysql query.

i can get expected result in raw mysql query but I want this to be done with the relationship.

so how can I combine below query with user model in a relationship,

SELECT * FROM users_membership WHERE id IN ( SELECT MAX(id) FROM users_membership GROUP BY users_id )

right now i am matching returned id with users table id in html table which is taking too much time to load.

0 likes
11 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20

If you want only to retrieve the last id, you can hack it this way in your relation

public function lastMembership(){
  return $this->hasOne('App\Membership')->orderBy('id', 'desc');
}

And then $users = User::with('lastMembership')->get(); or ($users = User::with('last_membership')->get();, I never know).

Deekshith's avatar

@vilfago Please help me out with this,

I have a user management application and there are around 15k users registered on our website. and this application has a simple blog module designed using laravel and I want to send email to all registered users once I post any updates in the blog. I am using sendgrid for this, but whenever I tried to send email, it is taking too much time in a loop and sometimes it gives timeout error. is there any way I can achieve this at high speed? and I need to hide all recipients email address. I know by using bcc we can hide all emails but need clarification regarding this.

Here is the sample code:

//converted email array to chunks

$recipient_chunks = array_chunk($email_array, 999);

//loop over user email address

foreach ($recipient_chunks as $user) {

Mail::queue('emails.updates_template',$email_data,function($message) use($email_data,$user) { $message->bcc($user)->subject('Latest Updates'); });

}

Vilfago's avatar

I'm not sure I'm the right person for this... and as this thread is resolved, probably no one will see it.

Maybe create a new thread with your question (and specifing which queue do you use, as it could have an impact on performance), but you can first have a look to these links : https://laravel.com/docs/5.7/notifications#queueing-notifications https://stackoverflow.com/questions/47991402/how-to-send-multiple-emails-in-laravel5-5

You can try to instead of bcc, if you send 15k email, every user will receive one mail, so don't see the other adress, no ?

Deekshith's avatar

i had converted to chunks, so for one loop, it will send for 1000 contacts at once. if I add "to" instead of bcc then every user will have to see other 999 users email address.

Vilfago's avatar

Which queue do you use which timeout for inserting 15 rows ?

Deekshith's avatar

This application had been developed using 4.2 version and I have not created any laravel queue, instead I have used Mail:: queue. Initially I am storing all email address in one array then I am converting that array to different chuncks with each Chuck has 1000 email addresses. And I am using forloop to send emails chuncks wise. Please check my previous reply to check my code.

Vilfago's avatar

And it was working without queue ???

Have you tried Mail::send instead?

Deekshith's avatar

Yes it was working but all my concern is time. Sometimes it will not even take 1 sec to complete and it was sending in background. But it suddenly stops to work in background and it is taking more than 2 min to complete the process.

Vilfago's avatar

What about setting a queue channel, and let the queue worker doing the hard stuff ?

But, I got the impression that we are far from the original subject. Maybe you will have some more valuable input in a new thread.

Please or to participate in this conversation.