【发布时间】:2016-06-07 05:15:57
【问题描述】:
我将在 Laravel 中创建多态关系,但我的表太旧了,而且它的命名约定不符合 laravel。我可以这样做吗?如何做?
【问题讨论】:
-
最好添加有关您当前数据库架构的更多信息。
-
你能添加你的代码吗?
标签: laravel polymorphism polymorphic-associations
我将在 Laravel 中创建多态关系,但我的表太旧了,而且它的命名约定不符合 laravel。我可以这样做吗?如何做?
【问题讨论】:
标签: laravel polymorphism polymorphic-associations
当然你可以直接设置你的表名和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');
}
}
【讨论】: