Eloquent eager loading, bug or intended behaviour? #33266
-
Description:When using eager loading on a model, another query's output in the relationship method changes. Steps To Reproduce:Model relations:
Have the default user model with relationship merchant <?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
public function merchant()
{
return $this->hasOne(\App\Merchant::class);
}
} Have a post model with an other relationship, depending on other data <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(\App\Comment::class)
->where('priviliged', auth()->user()->merchant->priviliged);
}
} When the comments are retrieved as I tried narrowing down the problem, and it looks like the nested query is the problem. <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
$user = User::find(3); // hard code user so this is no variable
dump($user->merchant->id); // retrieve the id to verify which data is retrieved
return $this->hasMany(\App\Comment::class)
->where('priviliged', auth()->user()->merchant->priviliged);
}
} When running When running I do not understand enough of the eager loading mechanism to determine if this is intended behaviour or a bug. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 7 replies
-
What's the result of |
Beta Was this translation helpful? Give feedback.
-
Can you log all the executed queries for both lazy and eager loading? |
Beta Was this translation helpful? Give feedback.
-
Please share the complete |
Beta Was this translation helpful? Give feedback.
-
Can you reproduce the issue on a fresh Laravel installation? |
Beta Was this translation helpful? Give feedback.
-
The behavior is surprising, but I wouldn't consider it a bug. Relationships aren't meant to be built dynamically with additional queries. Eager loading removes relationship constraints with Possible workarounds for your situation:
class User extends Authenticatable
{
protected $with = ['merchant'];
}
class Post extends Model
{
public function comments()
{
return $this->hasMany(\App\Comment::class)
->where('priviliged', auth()->user()->load('merchant')->merchant->priviliged);
}
} |
Beta Was this translation helpful? Give feedback.
The behavior is surprising, but I wouldn't consider it a bug. Relationships aren't meant to be built dynamically with additional queries.
Eager loading removes relationship constraints with
Relation::noConstraints()
and this also affects other queries that happen during this eager loading process.Possible workarounds for your situation: