【问题标题】:How to convert raw query into Laravel Eloquent way如何将原始查询转换为 Laravel Eloquent 方式
【发布时间】:2018-01-04 04:21:03
【问题描述】:

我有这个原始查询。 我怎样才能把这个转换成 Laravel eloquent。

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.

【问题讨论】:

  • resultsanswers是什么关系?
  • results有很多答案,答案属于结果。 @BalrajAllam

标签: laravel laravel-eloquent


【解决方案1】:

假设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();

【讨论】:

  • 感谢您的回答,我也可以获取关系以及结果。像使用上述查询的 with('relation') 一样?
  • 它们之间是什么关系?将其附加到您的问题中。
  • 我已经更新了问题,其次我在运行上述命令时收到“1066 - 不是唯一的表/别名:'答案'”。
  • 我已经编辑了我的答案,可能有效。如果没有,则在join方法的第一个参数中添加表别名as
【解决方案2】:

据我了解您的问题,您无法与联接建立关系。

请试试这个查询。

 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();

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

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2019-04-29
    • 2021-09-11
    • 2016-04-27
    • 2019-05-31
    • 2018-09-12
    • 2019-04-04
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多