php - Laravel eloquent relationships with foreign keys

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 :)
Answer
Solution:
This should work:
$jobId = 1;
$count = Message::whereHas('conversation.job', function($q) use ($jobId){
$q->where('id', $jobId);
})->count();
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught mysqli_sql_exception
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.