Laravel命名会话中的多态关系

时间:2016-06-07 05:15:57

标签: laravel polymorphism polymorphic-associations

我将在Laravel中创建多态关系,但是我的表太老了,它的命名约定不符合laravel。我可以这样做吗?

1 个答案:

答案 0 :(得分:1)

当然,您可以直接设置表名和FK列名 查看Realtion docs,如有必要,请查看Laravel APIsource 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');
    }
}