Answer the question
In order to leave comments, you need to log in
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');
}
}
$items = Item::with(['categories', 'user'])->orderBy('id', 'desc')->limit(5)->get();
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);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question