Laravel Eloquent中的多对多复杂多态关系

时间:2015-07-28 14:03:57

标签: laravel polymorphism laravel-5 eloquent polymorphic-associations

我正在我的项目中执行通知系统。我有一个数据库,我有用户和客户属于用户。可以为用户和客户添加通知。这就是我使用多对多变形关系的原因,这种关系在某种程度上运作良好。我无法处理为用户建立关系,这将为他和所有客户提供通知。

用户模型:

public function clients()
{
    return $this->hasMany('App\Models\Client');
}

public function notifications()
{
  return $this->morphToMany('App\Models\Notification', 'notifiable')
        ->withPivot('notice_time', 'user_seen')->withTimestamps();
  //Normally I would use it but here I will not catch notifications for clients
  return \Notification::whereHas('clients', function($q){
      $q->where('clients.user_id', $this->id);
    })->orWhereHas('users', function($q){
       $q->where('users.id', $this->id);
    });
  //The closest I have been using such code, however in this option I can't use wherePivot()
}

通知模型:

public function clients(){
    return $this->morphedByMany('App\Models\Client', $this->pivot)
        ->withPivot(self::USER_NOTICE_COLUMN, self::USER_SEEN_COLUMN)->withTimestamps();
}

public function users(){
    return $this->morphedByMany('App\Models\User', $this->pivot)
        ->withPivot(self::USER_NOTICE_COLUMN, self::USER_SEEN_COLUMN)->withTimestamps();
}

表格的小预览:

Notifiables     |Notifications | Clients | Users  |
----------------+--------------+---------+--------+
id              |id            |id       |id      |
notification_id |title         |user_id  |email   |
notifiable_id   |message       |name     |password|
user_seen       |              |surname  |        |
notice_time     |              |         |        |
notifiable_type |              |         |        |

是否有可能建立这样的关系,以便我可以使用用户通知功能用于用户对象并仍然是aple来使用查询范围?

1 个答案:

答案 0 :(得分:0)

似乎你无法轻易定义这种关系。从通知开始并加入数据透视表的最简单方法。

public function notifications(){
    return \Notification::
    whereHas('clients', function($q){
        $q->where('clients.user_id', $this->id);
    })->orWhereHas('users', function($q){
        $q->where('users.id', $this->id);
    })->join('notifiables', 'notifications.id', '=', 'notifiables.notification_id');
}