Laravel Polymorphic Relations Has Many Through

2019-05-05 07:21发布

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?

3条回答
相关推荐>>
2楼-- · 2019-05-05 08:09
// Topic Model

public function users()
{
    return $this->hasManyThrough('App\User', 'App\Subscriber', 'subscribable_id')->where('subscribable_type', array_search(static::class, Relation::morphMap()) ?: static::class);
}

Polymorphic hasManyThrough relationships are the same as any others, but with an added constraint on the subscribable_type, which can be retrieved from the Relation::morphMap() array, or by using the class name directly.

查看更多
ら.Afraid
3楼-- · 2019-05-05 08:13

Ok, i got a better solution

// Subscriber Model

use Notifiable;

public function receivesBroadcastNotificationsOn()
{
    return 'App.User.' . $this->user_id;
}


// Send Notification

Notification::send($post->subscribers, new TestNotification($post));
查看更多
我只想做你的唯一
4楼-- · 2019-05-05 08:15

In addition to Matt's approach, the following code also could be another solution:

//Topic Model
public function users()
{
    return $this->belongsToMany(User::class, 'subscribers', 'subscribale_id', 'user_id')
        ->where('subscribale_type', static::class);
}

In this way Subscriber treated as a pivot table and second argument is table name for pivot.

The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to. Read more here.

Consider the where clause after belongsToMany to filter only the current model.

查看更多
登录 后发表回答