I have a Subscriber Model
// Subscriber Model
id
user_id
subscribable_id
subscribable_type
public function user()
{
return $this->belongsTo('App\User');
}
public function subscribable()
{
return $this->morphTo();
}
And a Topic Model
// Topic Model
public function subscribers()
{
return $this->morphMany('App\Subscriber', 'subscribable');
}
And I want get all users through subscriber model, to notify them like
Notification::send($topic->users, new Notification($topic));
// Topic Model
public function users()
{
return $this->hasManyThrough('App\User', 'App\Subscriber');
}
Any ideas?
Polymorphic
hasManyThrough
relationships are the same as any others, but with an added constraint on thesubscribable_type
, which can be retrieved from theRelation::morphMap()
array, or by using the class name directly.Ok, i got a better solution
In addition to Matt's approach, the following code also could be another solution:
In this way
Subscriber
treated as a pivot table and second argument is table name for pivot.Consider the
where
clause afterbelongsToMany
to filter only the current model.