Skip to content

SQLite : foreign key as string provide null relation #30907

@sebastienfontaine

Description

@sebastienfontaine
  • Laravel Version: 6.9.0
  • PHP Version: 7.3.7
  • Database Driver & Version: SQLite (in memory)

Description:

With SQLite (in memory), relation is null when is loaded with "with" or "load" method, only when using a "string" as foreign key. The request is weird (see log).

It works well with Laravel 6.9 & MySQL.

It also works on Laravel 5.8.* & SQLite/MySQL.

Steps To Reproduce:

Create a roles table :

Schema::create('roles', function (Blueprint $table) {
            $table->string('code', 64)->primary();
            $table->string('name', 64);
});

Add a foreign key for users table :

Schema::table('users', function (Blueprint $table) {
            $table->string('role_code', 64)->default('USER');

            $table->foreign('role_code')->references('code')->on('roles')->onUpdate('restrict')->onDelete('restrict');
});

Add relation :

/**
* @return BelongsTo
*/
public function role(): BelongsTo
{
        return $this->belongsTo(Role::class);
}

Create and attach some data in seeders.

Test the code:

$user1 = User::first();
$user2 = User::with('role')->first();
$user3 = User::first()->load('role');

$this->assertNotNull($user1->role);  // OK
$this->assertNotNull($user2->role); // FAILED
$this->assertNotNull($user3->role); // FAILED

Log :

[2019-12-23 09:29:36] testing.INFO: $user1 :
[2019-12-23 09:29:36] testing.INFO: select * from "users" limit 1

[2019-12-23 09:29:36] testing.INFO: $user2 :
[2019-12-23 09:29:36] testing.INFO: select * from "users" limit 1
[2019-12-23 09:29:36] testing.INFO: select * from "roles" where "roles"."code" in (0)

[2019-12-23 09:29:36] testing.INFO: $user3 :
[2019-12-23 09:29:36] testing.INFO: select * from "users" limit 1
[2019-12-23 09:29:36] testing.INFO: select * from "roles" where "roles"."code" in (0)

[2019-12-23 09:29:36] testing.INFO: $user1 :
[2019-12-23 09:29:36] testing.INFO: select * from "roles" where "roles"."code" = ? limit 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions