Reputation: 3115
Stuck on this one tonight...so I'm building a messaging system which is comprised of tables as seen in this schema: http://www.laravelsd.com/share/8nBZmc
So a user may post a job to which another user can send that user a message regarding that job. This triggers a conversation to be created, a message to be posted (containing the ID of the user who sent it) and the two user_id's to be added to the conversation_user pivot table as participants.
In terms of relationships well a job HasMany conversations but BelongsTo a user, a conversation HasMany messages and BelongsTo a job, messages BelongTo a conversation etc etc etc.
My question is based on the schema, how could I show the total number of messages which relate to a job? I.e. How do I get the job ID and filter all the conversations that match the ID and then count the number of messages against each conversation? Is this straying into Query Builder land as opposed to Eloquent? Obvious solution is add job_id to messages table but that's duplication and I'm now too stubborn :)
Upvotes: 2
Views: 855
Reputation: 153150
This should work:
$jobId = 1;
$count = Message::whereHas('conversation.job', function($q) use ($jobId){
$q->where('id', $jobId);
})->count();
Upvotes: 2