Have you established Eloquent reationships or you need help with both query and relationships?
How do I retrieve the related models of related models of a model?
If the question is not clear enough, please consider reading this stackoverflow topic:
This time, though, I'll use different models. I'm making a basic Crime-tracking system. So, I have these tables:
Location Table -id -location_name
Crime Table -id -crime_name -location_id
Crime-Suspect Table -id -crime_id -suspect_id
Suspect Table -id -suspect_name
Basically, Crime belongs to many suspects and Suspect belongs to many crimes. Now, these three have their respective models: Location, Crime and Suspect.
Now, in the Location model, what I want to achieve is, I want to retrieve ALL of the suspects of all the crimes that is committed in that location. If you read the stackoverflow topic, I have the Group->Students->Subjects model there, and this is the SQL:
SELECT DISTINCT subject.id, subject.subject_name FROM tbl_student_subject studsubj LEFT JOIN tbl_student student ON student.id = studsubj.student_id RIGHT JOIN tbl_subject subject ON subject.id = studsubj.subject_id WHERE student.group_id = 1
Now, I want to apply this SQL in Eloquent as a relationship. If I can't, at least I just want to be able to retrieve the results as a collection of Suspect model.
The hasManyThrough doesn't work. It's made for a one-to-many model only, I think.
How do I do this in Eloquent? I hope you can help me. Thank you!
Change the method as:
public function suspects()
{
return $this->crimes->flatMap(function ($crime) {
return $crime->suspects;
})->unique('id');
}
Please or to participate in this conversation.