将查询生成器查询转换为Eloquent ORM

时间:2015-05-11 03:46:24

标签: mysql laravel laravel-4 orm laravel-5

我想将当前的查询转换为ORM。但是,我无法清楚地知道如何加入。

我当前的查询:

        $result=DB::table('tests')
            ->join('tests_matchs', 'tests_matchs.matched_tests_id', '=', 'tests.id')
            ->where('tests_matchs.user_id', '=', $UserId)
            ->where('tests_matchs.passed', '=', 'true')
            ->get();

2 个答案:

答案 0 :(得分:0)

假设您的关系设置正确,这应该有效:

$result = Test::with('tests_matchs' => function($query) user ($UserId){ 
    $query->where('user_id', '=', $UserId)
        ->where('passed', '=', 'true');
})->get()

答案 1 :(得分:0)

@Pawel Bieszczad你忘记了将数组作为参数,所以正确的查询将是

$result = Test::with(['tests_matchs' => function($query) uses ($UserId){ 
           $query->where('user_id', '=', $UserId)
                 ->where('passed', '=', 'true');
}])->get()