Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel's polymorphic relationships performance

Does anyone have any experience with performance of polymorphic relationships in Laravel? I need to have a settings tables for few different models, polymorphic relationship would be good here, I am wondering about performance, is it as good as if each model had its own settings table?

Settings table is simple and this is how the settings table would be like:

$table->increments('id');
$table->integer('foreign_id')->unsigned();
$table->string('key');
$table->string('value')->nullable();

I would shave off few tables that are needed for each models settings, just wondering if there would be performance issues using polymorphic setup?

If I decide to go with polymorphic then I would add these types to table:

        $table->string('has_settings_type');
        $table->biginteger('has_settings_id')->unsigned();

That's what laravel requires to add support for polymorphic relationships.

like image 508
niko craft Avatar asked Jul 27 '17 10:07

niko craft


1 Answers

An improvement to Jerodev's answer. Index order matters a lot.

Usually you would want to search for something like this
get all settings for a given model (foreign_object)

if you keep the index order like this (foreign_id,foreign_object), then sql will not be able to use index in order to execute the above query because the leftmost column in the index is not foreign_object

Thus the indexs should go like this

$table->index(['foreign_object', 'foreign_id']);
$table->index(['foreign_object', 'foreign_id', 'key']);
like image 106
Ravish Avatar answered Sep 20 '22 20:09

Ravish