[英]Laravel Builder Scope with Union and many-to-many relationship
I have a notifications table (and model) 我有一个通知表(和型号)
notifications table columns are thus: 因此,通知表列为:
id
title
body
is_public
...
I also have a users table (and model) 我也有一个用户表(和型号)
users table columns: 用户表列:
id
username
...
I also have a pivot notification_user table 我也有一个数据透视Notification_user表
columns: 列:
user_id
notification_id
many-to-many relationship is set on both Notification and User models thus: 在通知模型和用户模型上都设置了多对多关系,因此:
Notification.php
Notification.php
public function users()
{
return $this->belongsToMany('App\Api\V1\Models\User');
}
User.php
user.php的
public function notifications()
{
return $this->belongsToMany('App\Api\V1\Models\Notification');
}
Now inside Notification.php
I want to set a scope. 现在在
Notification.php
我想设置一个范围。 In the scope I need to get public notifications and the current user's private notifications in a single SQL query. 在作用域中,我需要在单个SQL查询中获取公共通知和当前用户的私人通知。 from my table structure, public notifications are where is_public == 1. Private notifications are associated on the pivot table.
从我的表结构来看,公共通知位于is_public ==1。私有通知与数据透视表关联。
to achieve this, inside my Notification.php
, I also have this setup: 为了实现这一点,在
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();
}
Now when I try Notification::publicAndPrivate()->get()
inside a controller, I get: 现在,当我在控制器中尝试
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))
Please I'll appreciate any help with getting this to work or a better solution. 请在使用此方法或提供更好的解决方案方面为您提供帮助。
I believe you should change: 我相信你应该改变:
return $user->notifications(); 返回$ user-> notifications();
to something else, for example: 例如:
return $query->where('user_id', $user->id);
or maybe 或者可能
return $query->whereHas('users', function($q) use ($user) {
$q->where('id', $user->id);
});
This is because in one query you are not using any join and in second you do and you are getting different number of columns for union parts. 这是因为在一个查询中您没有使用任何联接,而在第二查询中您使用了联接,并且得到的联合零件的列数也不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.