Laravel-5.4多态关系返回空数组

时间:2018-11-05 12:44:55

标签: laravel

我正在研究Laravel-5.4项目。我的数据库中有三个表usersarticlescomments

articles表的屏幕截图:

articles table

comments表的屏幕截图:

comments table

Article模型:

class Article extends Model
{
    public function comments() {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

Comment模型:

class Comment extends Model
{
    public function commentable() {
        return $this->morphTo();
    }
}

ArticleController包含以下方法:

public function showComments() {
    return Article::find(1)->comments;
}

showComments()方法上方将返回[](空数组)。我想返回包含id=1的文章的所有评论。有什么问题吗?

1 个答案:

答案 0 :(得分:2)

amp-carousel列应存储完全命名空间的模型名称,例如commentable_type。您是否手动输入了此信息?尝试将其更改为App\UserApp\User等,看看是否可行。

您可以在App\Article的启动方法中创建morphMap,以将这些命名空间别名为更具描述性的名称,如此处所做的。

AppServiceProvider

要导入public function boot() { Relation::morphMap([ 'User' => 'App\User', // etc ]); }

Relation