I have three models:
EmailTemplate
EmailSend
Attendee
An EmailSend references both an Attendee and an EmailTemplate:
class EmailSend extends MyBaseModel {
...
public function attendee()
{
return $this->belongsTo(AppModalsAttendee::class);
}
public function template()
{
return $this->belongsTo(AppModalsEmailTemplate::class);
}
...
}
and associated belongsTo relationships defined in the other direction.
A hasManyThrough relationship between EmailTemplate and Attendee doesn’t really make sense so I’ve not defined that.
My issue is that I want to make a HasMany relationship between EmailTemplate and EmailSend, where the referenced Attendee’s ‘is_cancelled’ field is 0
I currently have this:
class EmailTemplate extends MyBaseModel {
...
public function sends()
{
return $this->hasMany(AppModelsEmailSend::class)
->join('attendees', 'email_sends.attendee_id', '=', 'attendees.id')
->where('attendees.is_cancelled', 0);
}
...
}
which works, but is there a nicer way to do the join, which uses the existing defined relationships, rather than having to reference table names directly?
2
Answers
You can use a whereHas clause to achieve this without using direct joins:
You can use the
whereHas
method instead ofjoin
, but please be aware thatwhereHas
queries are generally slower compared tojoin
queries becausewhereHas
creates a exists query to fetch the results