Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Laravel Schema manages polymorphic associations out of the box?

I'd like to create some commentable models for a project, but I cannot find any references to create the comments migration script, I've only found this video on vimeo: Laravel 4 - Eloquent Collections & Polymorphic Relations.

Am I supposed to add the polymorphic columns explicitly?

Schema::create('comments',function($table){
    $table->increments('id');
    $table->text('body');
    $table->string('commentable_type');
    $table->integer('commentable_id');
    $table->timestamps();
});

Question comes as the builder do expects the programmer when a key is a foreign key as in $table->foreign('user_id')->references('id')->on('users');

like image 209
Ast Derek Avatar asked Jan 11 '13 03:01

Ast Derek


People also ask

What is polymorphic relationships in laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is polymorphic association in sql?

Polymorphic relationships work by using a lookup table with an additional column specifying which table the foreign key should reference. In non-polymorphic relationships, the foreign keys references a primary ID in a specific table.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


1 Answers

Laravel ~4.1 has a method to accomplish this:

$table->morphs('itemable');

Creates:

itemable_id
itemable_type
table_name_itemable_id_itemable_type_index

Second optional parameter is a replacement index name if the index is too long. The signature is:

public function morphs($name, $indexName = null);
like image 81
andrewhl Avatar answered Oct 04 '22 12:10

andrewhl