Skip to content

whereDoesntHave not produce correct query when use with nullableMorphs #54315

Closed
@mix5003

Description

@mix5003

Laravel Version

11.39.1

PHP Version

8.2.12

Database Driver & Version

sqlite / mysql

Description

When use whereDoesntHave with nullableMorphs relation. it will not count nullable as dosent have.

Steps To Reproduce

prepare project

  1. create new project with laravel 10/11
  2. create MainTable model by php artisan make:model -m MainTable
  3. add $table->nullableMorphs('relate'); to MainTable migration file
  4. add morphTo relation to MainTable Model file public function relate(){ return $this->morphTo(); }
  5. create Relate1model by php artisan make:model -m Relate1
  6. migrate by php artisan migrate

test by this in php artisan tinker

use App\Models\MainTable;
use App\Models\Relate1;

$r1 = new Relate1();
$r1->save();


$m1 = new MainTable();
$m1->save();

$m2 = new MainTable();
$m2->relate()->associate($r1);
$m2->save();

DB::enableQueryLog();
echo MainTable::has('relate')->count(); // 1
echo MainTable::whereDoesntHave('relate')->count(); // 0 expect 1

var_dump(DB::getQueryLog());

it produce this query

select count(*) as aggregate from "main_tables" where (("main_tables"."relate_type" = ? and not exists (select * from "relate1s" where "main_tables"."relate_id" = "relate1s"."id")))

but it should be (add "main_tables"."relate_type" is null or

select count(*) as aggregate from "main_tables" where ("main_tables"."relate_type" is null or ("main_tables"."relate_type" = ? and not exists (select * from "relate1s" where "main_tables"."relate_id" = "relate1s"."id")))

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