Khirad Zahra
Khirad Zahra

Reputation: 893

How to convert raw query into Laravel Eloquent way

I have this raw query. How can i convert this one into 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.

Upvotes: 0

Views: 57

Answers (2)

Asim Shahzad
Asim Shahzad

Reputation: 1609

As far i understood your question,you can't get relationship with joins.

Please try this query.

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

Now you can run another query to get relational data.

Upvotes: 1

Cong Chen
Cong Chen

Reputation: 2436

Assume that Result is table results's model:

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

Upvotes: 0

Related Questions