E
E
Eugene2015-01-27 17:55:03
Laravel
Eugene, 2015-01-27 17:55:03

Many to Many Eager Loading, how to do without join?

There are 3 models Item, User, Category

class Item extends Eloquent {
    public $timestamps = false;
    protected $table = 'item';

    public function categories() {
        return $this->belongsToMany('Category', 'item_category', 'itemId', 'categoryId');
    }

    public function user() {
        return $this->belongsTo('User', 'userId')->select(['id', 'login', 'role']);
    }
}

class User extends Eloquent {
    public $timestamps = false;
    protected $table = 'user';

    public function items() {
        return $this->hasMany('Item', 'userId', 'id');
    }
}

class Category extends Eloquent {
    public $timestamps = false;
    protected $table = 'category';

    public function items() {
        return $this->belongsToMany('Item', 'item_category', 'categoryId', 'itemId');
    }
}

Entering the last 5 Items with users and categories
$items = Item::with(['categories', 'user'])->orderBy('id', 'desc')->limit(5)->get();

These are the queries generated by Laravel
select * from `item` order by `id` desc limit 5;

select `id`, `login`, `role` from `user` where `user`.`id` in (1,2,3,4,5);

select `category`.*, `item_category`.`itemId` as `pivot_itemId`, `item_category`.`categoryId` as `pivot_categoryId`
from `category` inner join `item_category` on `category`.`id` = `item_category`.`categoryId` 
where `item_category`.`itemId` in (100000, 99999, 99998, 99997, 99996);

He takes out 5 items, collects user IDs, then takes out 5 users, that's all right.
But with the many_many categories, the logic is incomprehensible, why does he do a join?
Why, by analogy, not make a query from item_category, and then not get categories by id from the category table?
Or maybe I don't know something, and in laravel it is possible to make such behavior?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gladkovskiy, 2015-01-27
@SMGladkovskiy

There can be selection conditions for both pivot tables and related entities. To fit all this, a select is made on the pivot with a restriction on the id of the "near" entity.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question