Skip to content

Eloquent Relation ignores its NULL column #29622

Closed
@emadha

Description

@emadha
  • Laravel Version: 5.8.#
  • PHP Version: 7.#.#
  • Database Driver & Version: MariaDB

Description:

Eloquent with a relation, say HasMany, doesn't care about the NULL column and keep trying to get the Model.

Steps To Reproduce:

php artisan make:model Category -mc
Migaration should have something like category_id // like a parent category

Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('category_id')->nullable(); // <- parent category
            $table->string('title');
            ...
        });

Model App\Category:

/**
  * Get the parent category
  *
  * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
  */
 public function category()
 {
     return $this->belongsTo(Category::class);
 }

Until now it's fine, But:

Add the $with = ['category'] to the Eloquent and you'll get a query like this when the category_id is NULL:

Debugbar final query:
select * from `categories` where 0 = 1

App\Category->category()->toSql() Builder query:
select * from `categories` where `categories`.`id` is null

And you can get the same result if you get the relation of a null colum without using the $with:
$CategoryWithCategoryIDNULL = Category->category()->toSql();

remember The table's name is category and it has ID and another column called category_id,
you can name it parent_id if you got confused with double the names.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions