Laravel Builder Scope with Union 和多对多关系

Laravel Builder Scope with Union and many-to-many relationship


我有一个通知 table(和模型)
因此,通知 table 列为:

id
title
body
is_public
...

我也有一个用户table(和型号)
用户 table 列:

id
username
...

我也有一个支点notification_usertable
列:

user_id
notification_id

通知和用户模型都设置了多对多关系,因此:

Notification.php

public function users()
{
    return $this->belongsToMany('App\Api\V1\Models\User');
}

User.php

public function notifications() 
{
    return $this->belongsToMany('App\Api\V1\Models\Notification');      
}

现在在 Notification.php 我想设置一个范围。在范围内我需要获得 public 通知和当前用户的 单个 SQL 查询中的私人通知。从我的 table 结构中,public 通知位于 is_public == 1 的位置。私有通知与枢轴 table.

关联

为了实现这个,在我的 Notification.php 中,我也有这个设置:

public function scopePublicAndPrivate(Builder $query)
{
    return $this->public($query)->union($this->private($query));
}
public function scopePublic(Builder $query)
{
    return $query->where('is_public', 1);
}
public function scopePrivate(Builder $query)
{
    $user = JWTAuth::parseToken()->authenticate(); //using JWT to get a user.
    return $user->notifications();
}

现在,当我在控制器中尝试 Notification::publicAndPrivate()->get() 时,我得到:

Illuminate\Database\QueryException with message 'SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select * from `notifications` where `is_public` = 1) union (select * from `notifications` inner join `notification_user` on `notifications`.`id` = `notification_user`.`notification_id` where `notification_user`.`user_id` = 1))

如果您能帮助我解决这个问题或找到更好的解决方案,我将不胜感激。

我认为你应该改变:

return $user->notifications();

到别的东西,例如:

return $query->where('user_id', $user->id);

或者也许

return $query->whereHas('users', function($q) use ($user) {
   $q->where('id', $user->id);
});   

这是因为在一个查询中您没有使用任何联接,而在第二个查询中您使用了联接,并且您得到的并集部分的列数不同。