Laravel 4.2 Eloquent relationship leftjoin ON复杂

时间:2014-11-29 08:01:13

标签: mysql laravel-4 relational-database left-join eloquent

Mysql查询

    LEFT JOIN matches as m
    ON sched.league_id = m.leagueid
    AND sched.starttime >= m.start_time
    AND (sched.team_a_id = m.radiant_team_id AND sched.team_b_id = m.dire_team_id)
    OR (sched.team_b_id = m.radiant_team_id AND sched.team_a_id = m.dire_team_id)

Laravel Eloquent

    ->leftJoin('matches as m', function($join){
        $join->on('league_id','=','m.leagueid');
        $join->on('starttime','=','m.start_time');
        // @TODO  AND (sched.team_a_id = m.radiant_team_id AND sched.team_b_id = m.dire_team_id)
        // @TODO OR (sched.team_b_id = m.radiant_team_id AND sched.team_a_id = m.dire_team_id)
    })

问题

  • 如何离开加入 使用Laravel Eloquent (某事物=东西=某事物)或(某物=某物和某物=某物)

2 个答案:

答案 0 :(得分:1)

你的MySQL查询首先是错误的,我确定这是你想要的:

LEFT JOIN matches as m
ON sched.league_id = m.leagueid
AND sched.starttime >= m.start_time
AND (
  sched.team_a_id = m.radiant_team_id AND sched.team_b_id = m.dire_team_id
  OR sched.team_b_id = m.radiant_team_id AND sched.team_a_id = m.dire_team_id
)

现在,不幸的是Laravel无法建立这种联接。

所以唯一的方法就是:

->leftJoin('matches as m', function ($j) {
   $j->on('league_id','=','m.leagueid')
     ->on('starttime','=','m.start_time')
     ->on(sched.team_a_id = m.radiant_team_id)
     ->on(sched.team_b_id = m.dire_team_id)
     ->orOn('league_id','=','m.leagueid')
     ->on('starttime','=','m.start_time')
     ->on(sched.team_b_id = m.radiant_team_id)
     ->on(sched.team_a_id = m.dire_team_id);
})

或使用原始语句(注意DB::raw中的括号):

->leftJoin('matches as m', function ($j) {
   $j->on('league_id','=','m.leagueid')
    ->on('starttime','=','m.start_time')
    ->on(
     DB::raw( '(sched.team_a_id',
     '=', 
     DB::raw('m.radiant_team_id AND sched.team_b_id = m.start_time'
  .'OR sched.team_b_id = m.radiant_team_id AND sched.team_a_id = m.start_time)')
    );
})

答案 1 :(得分:0)

             $join->on('league_id','=','m.leagueid')
             ->on('starttime','<=','m.start_time')
             ->on(DB::raw('m.radiant_team_id'), 'IN', DB::raw('(team_a_id,team_b_id)'))
             ->on(DB::raw('m.dire_team_id'), 'IN', DB::raw('(team_a_id,team_b_id)'));