0

Look I know it's not best-practice, strictly speaking, but setting foreign keys in Laravel is consistently an enormous pain.

Something as simple as this just fails maybe 70% of the time. Sometimes with good reason, and sometimes just... because it feels like it. Naturally there's no meaningful error message either.

    Schema::table('accounts', function(Blueprint $table){
        $table->integer('package_id')->unsigned();
        $table->foreign('package_id')->references('id')->on('packages')->onDelete('set null');
    });

Now, the app runs totally fine and all relationships work correctly without setting foreign keys in the database, so is there any actual harm in just ignoring them entirely?

MitchEff
  • 1,417
  • 14
  • 29
  • that setting fails specifically because you use `Set Null` on a *Non Nullable* field (the package_id). Either use `$table->integer('package_id')->unsigned()->nullable()` OR use a different constraint on the `onDelete`, such as `onDelete('cascade')`. – Jaime Rojas Oct 02 '18 at 02:33
  • -1 because question is advocating bad practice and laziness in programming. Instead asking this, OP should search for material to see what is advantage of having well set relations in DB. Very upside down way of thinking, I'd say from laziness, what could be conclusions reading the post. – Tpojka Oct 02 '18 at 08:51

1 Answers1

3

This Laravel syntax $table->foreign('package_id')->references('id')->on('packages')->onDelete('set null') does two main things:

  1. Creates foreign key (and its constraint). The benefit of this is data Consistency (the C in ACID). Not using foreign key means table consistency is not guaranteed by DBMS (eg. having packages referring to deleted accounts). This may not be an issue if data consistency is not really required or handled by other layer (eg. application layer). Read this answer for more details.
  2. Creates foreign key index. The benefit is better performance on query that use the foreign key (in this case package_id). This benefit becomes more significant when the number of rows are big. If the tables won't store big number of rows, you can ignore this. Read more details in this article.
Yohanes Gultom
  • 3,782
  • 2
  • 25
  • 38