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');
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.
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.
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.
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);
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