laravel - Relationship results automatically coming out? -
i have series of relations on model, here 1 of them.
class product extends model{ public function user(){ return $this->belongstomany('\app\user'); } } i rows with:
$data = product::all() and these looped through so:
foreach ($data $value) { var_dump($value->title); } my understanding if wished relational data come out, need like:
$data = product::with('user')->get(); but without above , doing all() still can access user:
foreach ($data $value) { var_dump($value->title->user); } why this?
relationship results automatically coming out?
no, when do
$data = product::all(); foreach ($data $value) { var_dump($value->title); } you doing this:
select * products but on foreach, since trying access property wasn't loaded, doing new query, behind scenes laravel fetching user. represents n + 1 query problem, if have 25 products run 26 queries (25+1):
select * products select * users id = ? (x25) that's why have eager loading option,
$data = product::with('user')->get(); foreach ($data $value) { var_dump($value->title->user); } doing running 2 queries
select * products select * users id in (1, 2, 3, 4, 5, ...) so it's choose method use, if aren't iterating products users, eager loading unnecessary , usual all() fine;
Comments
Post a Comment