我将在Laravel中创建多态关系,但是我的表太老了,它的命名约定不符合laravel。我可以这样做吗?
答案 0 :(得分:1)
当然,您可以直接设置表名和FK列名 查看Realtion docs,如有必要,请查看Laravel API或source code
如果你有
posts
id - integer
title - string
body - text
comments
id - integer
post_id - integer
body - text
likes
id - integer
likeable_id - integer
likeable_type - string
然后你的代码将是
<?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');
}
}