首页 文章

如何将原始查询转换为Laravel Eloquent方式

提问于
浏览
0

我有这个原始查询 . 我怎样才能将这一个转换为Laravel雄辩 .

SELECT * FROM `results` AS q
INNER JOIN `answers`AS a ON q.question_id = a.question_id 
AND q.team1 = a.team1 
AND q.team2 = a.team2 
AND q.score1 = a.score1

// Table relationships.
results hasMany answers.
results hasMany predictions.
Prediction is another model here.

2 回答

  • 1

    到目前为止,我理解你的问题,你无法与连接 Build 关系 .

    请尝试此查询 .

    Result::join('results as q', function ($join) {
                $join->on('answers.question_id', '=', 'q.question_id')
                    ->on('user_answers.team1', '=', 'q.team1')
                    ->on('user_answers.team2', '=', 'q.team2')
                    ->on('user_answers.score1', '=', 'q.score1')
                    ->on('user_answers.score2', '=', 'q.score2');
            })->get();
    

    现在,您可以运行另一个查询来获取关系数据 .

  • 0

    假设 Result 是表 results 的模型:

    Result::join('answers', function ($join) {
        $join->on('answers.question_id', '=', 'results.question_id')
             ->on('answers.team1', '=', 'results.team1')
             ->on('answers.team2', '=', 'results.team2')
             ->on('answers.score1', '=', 'results.score1');
    })->get();
    

相关问题