Laravel 5 - 带条件的多态性注释 table

Laravel 5 - polymorphism comments table with conditions

在我的程序中,用户可以评论新闻和比赛。

Comment table:

id - (primary)
comment_type - (1 =  match, 2 = news)
comment_id (The id to the type. News.id or match.id)
profile_id
text

我的关系有问题,因为评论 table 可以存储新闻评论和匹配评论,因此我没有外键。

我试过这样做:

Comment model

 public function comment()
    {
        return $this->morphTo();
    }

News model

public function comments()
    {
        return $this->morphMany('App\Comment', 'comment');
    }

我希望评论在一个 table 而不是 match_comment 和 news_comment table.

当我调用 $news->comments 时,它 returns 一个空数组。

有人可以帮忙吗?

提前致谢 安德烈亚斯

您正在尝试将 Laravel 的内置多态关系支持与不支持它的数据库结构一起使用。 relevant section of the manual 说的是这样的(针对您的情况做了一些调整):

The key fields to notice here are the [commentable_id] and [commentable_type] on the comments table. The ID will contain the ID value of, in this example, the owning [match] or [news], while the type will contain the class name of the owning model [i.e. not an integer like 1 = match and 2 = news]. This is what allows the ORM to determine which type of owning model to return when accessing the [commentable] relation.

我不确定您是否能够改变它以使用给定的 table 结构。如果可以,您应该更改它 - 或者您可能需要在模型上坚持使用自定义查询或便捷方法来访问此数据。

因此,为了回答您的实际问题,我相信您最终会得到 $news->comments 的空结果,因为在幕后 运行 的查询类似于:

SELECT * FROM `comments` WHERE comment_id = {$news->id} AND comment_type = 'App\News';

编辑

根据文档中的示例结构,您可能需要一个 table 结构,如下所示:

news
    id - integer
    other columns...      

matches
    id - integer
    other columns...

comments
    id - integer
    text - string
    commentable_id - integer
    commentable_type - string

然后您还需要调整您的新闻和比赛 classes 以具有:

public function comments()
{
    return $this->morphMany('App\Comments', 'commentable');
} 

注意 commentable 参数指的是应该在 Comment class:

上的方法
class Comment extends Model {

    public function commentable()
    {
        return $this->morphTo();
    }
}

(很重要,因为您已经表明您当前正在使用 comment() 作为方法名称)