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.
An improvement to Jerodev's answer. Index order matters a lot.
Usually you would want to search for something like thisget 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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With