I do not really understand what is the method of laravel for eager loading and solve the problem of N+1 query and what is going under hood. So I decided the test it myself to see result!
So I designed a simple many to many relationship that every tgchannel(telegram channel) has many tags and every tag has many tgchannel.
namespace App;
use Illuminate\Database\Eloquent\Model;
class tgchannel extends Model
{
public function tags() {
return $this->belongsToMany('App\tag');
}
}
/////////////////////////////
class tag extends Model
{
//
public function tgchannels() {
return $this->belongsToMany('App\tgchannel');
}
I used eager loading to load tags relationship in a controller method, according to laravel documentation and output resulting sql with this technique:
public function test()
{
$all_channels = tgchannel::with(['tags'])->toSql();
echo $all_channels.'<br>';
$all_channels = tgchannel::with(['tags'])->get();
foreach ($all_channels as $channel) {
$sql = $channel->tags()->toSql();
echo $sql.'<br>';
}
}
in the test database, I had 12 tgchannels that each one had a tag. and finally this is the result:
select * from `tgchannels`
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
select * from `tags` inner join `tag_tgchannel` on `tags`.`id` = `tag_tgchannel`.`tag_id` where `tag_tgchannel`.`tgchannel_id` = ?
and you can see that the queries that executed is not 2 and is N+1 query executed that similar to common lazy loading!
what is the problem??