You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a model has an overridden newQuery() method, loading a morphTo relation via ->load() results in an incorrect query being generated.
Steps To Reproduce
class User extends Model
{
protected $fillable = ['name'];
}
class Image extends Model
{
protected $fillable = ['url'];
public function newQuery()
{
return parent::newQuery()->whereNotNull('url');
}
public function owner()
{
return $this->morphTo('owner');
}
}
$image = Image::find(1);
//An invalid query is generated for the related model:
//select * from "users" where "url" is not null and "users"."id" in (1)
$image->load('owner');
We'll need more info and/or code to debug this further. Can you please create a repository with the command below, commit the code that reproduces the issue as one separate commit on the main/master branch and share the repository here?
There is no issue when registering this condition as a global scope.
It seems the issue is caused in Illuminate/Database/Eloquent/Relations/MorphTo.php:149
where the call to ->mergeConstraintsFrom($this->getQuery()) merges where condition from the images table into the users table (as in the example above).
Laravel Version
11
PHP Version
8.4
Database Driver & Version
No response
Description
When a model has an overridden
newQuery()
method, loading a morphTo relation via->load()
results in an incorrect query being generated.Steps To Reproduce
Link to code snippet.
The text was updated successfully, but these errors were encountered: