Closed
Description
Laravel Version
11.6.0
PHP Version
8.2.5
Database Driver & Version
MySQL 8.0.32
Description
When using HasMany
or MorphMany
relations, if the model's primary key is null
, it creates an impossible query:
select * from `media` where `media`.`model_type` = 'App\Models\Employer' and `media`.`model_id` is null and `media`.`model_id` is not null limit 1
select count(*) as aggregate from `employers` where `employers`.`parent_id` is null and `employers`.`parent_id` is not null and `employers`.`deleted_at` is null
In the above scenario, the employer model utilized has been fetched using a select
statement which transforms the primary key (select('id as value')
). However, when attempting to fetch relations on this model, it will still call the database.
Seemingly, this should have been fixed with #26992 but I suppose when it is a direct relation query it doesn't use getResults
and therefore doesn't bail.
Steps To Reproduce
- Create a model with a
parent_id
:
Schema::create('employers', function (Blueprint $table) {
$table->unsignedBigInteger('parent_id')->nullable();
});
- Seed a parent and child:
$employer = \App\Models\Employer::create();
\App\Models\Employer::create(['parent_id' => $employer->id]);
- Define a relation:
public function children(): HasMany
{
return $this->hasMany(Employer::class, 'parent_id', 'id');
}
- Fetch the Employer using a
select
and call the relation as query:
$employer = Employer::select('id as value')->first()->children()->count();