【发布时间】:2016-12-31 17:15:04
【问题描述】:
我无法在 laravel 上创建这个 sql 查询:
select * from `events_theatre` where
event_id IN (
select id from events where (`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` ='theatre') and `events`.`deleted_at` is null
)
or event_id IN (
select id from events inner join events_managers on events.id = events_managers.event_id and events_managers.user_id = 1
)
and `events_theatre`.`deleted_at` is null
Events_Theatre 模型具有这种关系:
public function event()
{
return $this->hasOne('App\MyEvent', 'id');
}
虽然 MyEvent 模型有这种关系:
public function managers()
{
return $this->belongsToMany('App\User', 'events_managers', 'event_id', 'user_id');
}
实际上,Events_Theatre 模型是 Event 模型,Event 模型可能有很多经理,但只有 1 个管理员。
我需要获取用户是管理员或经理之一的 Events_Theatre(和他们的 MyEvent)。
我尝试了这个雄辩的查询:
$list = App\Events_Theatre::whereIn('event_id', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre'])
->orWhereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
});
但我得到了这个 sql 查询:
select * from `events_theatre` where
exists (
select * from `events` where (
`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` = 'theatre'
) or exists (
select * from `users` inner join `events_managers` on `users`.`id` = `events_managers`.`user_id` where `events_managers`.`event_id` = `events`.`id` and `user_id` = 1
)
and `events`.`deleted_at` is null
) and `events_theatre`.`deleted_at` is null
但这是错误的。我该如何解决这个问题?
谢谢
更新
我得到了答案。这是我用的雄辩的代码:
$list = Events_Theatre::whereHas('event', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre']);
})->orWhereHas('event', function ($query) {
$query
->whereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
})->get();
【问题讨论】:
-
第一个选择存在的字段 user_id 和 event_type 在哪里?
-
您能否明确说明您要搜索的条件。从您粘贴的所有不同的 sql 中推断出来有点令人困惑。
-
我需要获取用户是管理员或经理之一的 Events_Theatre(和他们的 MyEvent)。
标签: laravel many-to-many relationships