【问题标题】:Many To Many Complex Polymorphic Relationship in Laravel EloquentLaravel Eloquent 中的多对多复杂多态关系
【发布时间】:2015-10-19 03:31:42
【问题描述】:

我正在我的项目中做通知系统。我有一个数据库,其中有用户和属于用户的客户。可以为用户和客户端添加通知。这就是我使用多对多多态关系的原因,它在一定程度上运作良好。我无法为用户建立关系,这将为他和所有客户接收通知。

用户模型:

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

表格小预览:

通知 |通知 |客户 |用户 | ----------------+--------------+---------+-------- + id |id |id |id | notification_id |title |user_id |email | notifiable_id |消息 |名称 |密码| user_seen | |姓氏| | 通知时间 | | | | 通知类型 | | | |

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

【问题讨论】:

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


    【解决方案1】:

    看来你不能轻易定义这样的关系。从通知开始并加入数据透视表的最简单方法。

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

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2019-06-13
      • 2019-03-26
      • 1970-01-01
      • 2013-05-15
      • 2014-09-27
      • 1970-01-01
      • 2013-05-27
      • 2016-11-03
      相关资源
      最近更新 更多