Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

duellsy's avatar

Initial database schema

I noticed that the base schema contains no foreign keys, is there a certain reason this might be the case?

I would have thought foreign keys would always be recommended, both for indexing as well as data cleanup (with cascading deletes), am I missing something here?

0 likes
2 replies
nolros's avatar

@duellsy it does contain unless I'm missing your point e.g.

       Schema::create('experience_persona', function(Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->unsignedInteger('persona_id')->index();
            $table->foreign('persona_id')->references('id')->on('personas')
                ->onDelete('cascade');
            $table->unsignedInteger('experience_id')->index();
            $table->foreign('experience_id')->references('id')->on('experience')
                ->onDelete('cascade');
        });

jekinney's avatar
jekinney
Best Answer
Level 47

Eloquent doesn't use foreign keys like a typical sql query. It's part of the active directory pattern.

Let's say you eager load a relationship of one to many. Retrieving one row from the main model and X amount from the relationship. Normal sql query you'd use a join and grab all data in one query.

This puts more pressure (so to speak) on the db to get all the data and figure it out. Active directory though puts that pressure on your programming language (this case php). In short joins are not used but instead two queries are run. The trade off is two more efficent and easier queries. Depending on how much data and proper INDEXING generally has better performance in response time.

To answer your question, spark schema index() instead of foreign keys, though I'm 99% sure it has some. And db clean up is up to the programmer. You don't expect sql to clean up unused files like images when you delete the path in the db, right? Instead you check if the file exists and if it does remove it then delete the reference to the path. Keeping your db clean via relationships is the same way.

1 like

Please or to participate in this conversation.