2016-08-24 17 views
0

に私はlaravel上でこのSQLクエリを作成することはできませんよ複数:Laravel:句は、多対多の関係

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モデルはイベントモデルであり、Ev entモデルには多くの管理者がいますが、管理者は1人だけです。

ユーザーが管理者または管理者の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(); 
+0

を試すことができますか? –

+0

検索する条件を明示してください。あなたがペーストしたすべての異なるSQLから推測するのはちょっと混乱します。 –

+0

ユーザーが管理者または管理者の1人であるEvents_Theatre(およびそのMyEvent)を取得する必要があります。 –

答えて

0

あなたが存在に選択する最初の、表があなたのフィールドUSER_IDとEVENT_TYPEされた場合にはhas方法

App\Events_Theatre::has('event')->orhas('managers')->get();