Ltloafer's avatar

Models with foreign key fails in sqlite (with foreign keys enabled)

This is driving me a little crazy. I can easily work round it but it seems a shame to change the code to suit tests with SQlite.

I migrate my 'crop_requests' table.


Schema::create('crop_requests', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('business_id');
            $table->string('request_reference');
 	    $table->foreignId('supplier_business_id')->references('id')->on('businesses');
            $table->string('crop_reference')->nullable();
            $table->integer('supplier_member_reference')->nullable();
            $table->integer('requested_crop_reference')->nullable();
            $table->integer('requested_crop_id')->nullable();
            $table->integer('user_follows_croplink_id')->nullable();
            $table->string('status')->nullable();
            $table->timestamp('read')->nullable();
            $table->timestamps();
        });

I then migrate my 'businesses table'.

From my Business model

public function incomingCropRequests()
{
        return $this->hasMany(CropRequest::class, 'supplier_business_id');
}

When I run this with mysql it is fine but SQlite tests returns empty

$cropRequests = $this->loggedInBusiness->incomingCropRequests;

If I change it to the following it runs fine on both databases.

$cropRequests = CropRequest::where('supplier_business_id', \Auth::user()->business->id)->get();

The models are in the databases okay each time. Foreign keys are enabled.

As per usual I'm probably missing something blindingly obvious but can't spot it at the moment!

On Laravel 7.30.1 , SQLite 3.19.3.

0 likes
6 replies
Tray2's avatar

Why don't you just use the second syntax if it works for both databases?

Ltloafer's avatar

That's a very good point @tray2

Since I like to run tests with SQLite for the speed it just means that I have to avoid this foreign key syntax from now on as I don't understand why it fails.

Ltloafer's avatar

Hi @fylzero . Yep, I've got them enabled and can see in the dumped env variable that its there. I think I'll have to avoid them too.. Thanks

Please or to participate in this conversation.