Laravel多态关系有很多通过 [英] Laravel Polymorphic Relations Has Many Through

查看:89
本文介绍了Laravel多态关系有很多通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个订户模型

// Subscriber Model

id
user_id
subscribable_id
subscribable_type

public function user()
{
    return $this->belongsTo('App\User');
}

public function subscribable()
{
    return $this->morphTo();
}

和主题模型

// 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));

Notification::send($topic->users, new Notification($topic));

// Topic Model


public function users()
{
    return $this->hasManyThrough('App\User', 'App\Subscriber');
}

有什么想法吗?

推荐答案


// 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);
}

多态hasManyThrough关系与其他任何关系相同,但是对subscribable_type的附加约束是可以从Relation::morphMap()数组或直接使用类名检索的.

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.

这篇关于Laravel多态关系有很多通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆