Skip to content

Unnecessary queries when using HasOneOrMany when primary key is null  #51266

Closed
@Yinci

Description

@Yinci

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

  1. Create a model with a parent_id:
Schema::create('employers', function (Blueprint $table) {
    $table->unsignedBigInteger('parent_id')->nullable();
});
  1. Seed a parent and child:
$employer = \App\Models\Employer::create();
\App\Models\Employer::create(['parent_id' => $employer->id]);
  1. Define a relation:
public function children(): HasMany
{
    return $this->hasMany(Employer::class, 'parent_id', 'id');
}
  1. Fetch the Employer using a select and call the relation as query:
$employer = Employer::select('id as value')->first()->children()->count();

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions