Reputation: 1753
I am going to create polymorphic relations in Laravel but my tables are so old and it's naming conventions are not according to laravel. Can I do this and how ?
Upvotes: 1
Views: 1204
Reputation: 4795
Of course you can set your table name and FK column names directly.
Look over Realtion docs and if necessary in Laravel API or source code
If you have
posts
id - integer
title - string
body - text
comments
id - integer
post_id - integer
body - text
likes
id - integer
likeable_id - integer
likeable_type - string
Then your code will be
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
/**
* Get all of the owning likeable models.
*/
public function likeable()
{
return $this->morphTo('likeable', 'likeable_type', 'likeable_id');
}
}
class Post extends Model
{
/**
* Get all of the post's likes.
*/
public function likes()
{
return $this->morphMany('App\Like', 'likeable', 'likeable_type', 'likeable_id');
}
}
class Comment extends Model
{
/**
* Get all of the comment's likes.
*/
public function likes()
{
return $this->morphMany('App\Like', 'likeable', 'likeable_type', 'likeable_id');
}
}
Upvotes: 1