azngunit81
azngunit81

Reputation: 1604

Laravel Relationship Eager Loading belongsTo incorrect

I have a table called books. I have a table called scores which is based on a metric on 100.

This is the select I wish to preform:

SELECT * FROM books AS b LEFT JOIN scores AS s ON s.media_type_id = 1 AND s.media_id = b.id ORDER BY s.sorting_score

I am using Eloquent ORM only (not the full framework)

inside Book Model:

public function score()
{
    return $this->belongsTo('Score', 'scores', 'media_id','id');
}

is the relationship.

$books = Book::with(array('score' => function($query) use ($id)
            {
               $query->where('media_type_id','=',$id)->orderBy('sorting_score','ASC');
            }))->get();

its not yielding the same result.

I have two questions: Did my concept of Eager Loading is wrong? If so - how do I do join appropriately in Laravel in order to mimic SQL.

Upvotes: 0

Views: 987

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

Eager loading in Eloquent runs another query with WHERE IN clause, so probably not what you expected.

This is how you build that query:

$books = Book::leftJoin('scores s', 'scores.media_id', '=', 'books.id')
             ->where('s.media_type_id', '=', $typeId)
             ->orderBy('s.sorting_scores')
             ->get();

And by the way the relation definition is wrong. That's how it should look like:

// Book model
public function score()
{
    return $this->hasOne('Score', 'media_id');
      // possibly this would be necessary too:
      // ->where('media_type_id', 1); // assuming 1 for type Book 
}

then the other relation:

// Score model
public function book()
{
    return $this->belongsTo('Book', 'media_id');
      // ->where('media_type_id', 1);
}

Upvotes: 1

Related Questions