【问题标题】:Laravel-5.4 Polymorphic relation returns empty arrayLaravel-5.4 多态关系返回空数组
【发布时间】:2018-11-05 21:24:36
【问题描述】:

我正在开发一个 Laravel-5.4 项目。我的数据库中有三个表 usersarticlescomments

articles 表截图:

comments 表的屏幕截图:

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 的所有cmets。有什么问题?

【问题讨论】:

    标签: laravel


    【解决方案1】:

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

    您可以在 AppServiceProvider 的引导方法中创建一个 morphMap 以将这些命名空间别名为更具描述性的名称,就像您在此处所做的那样。

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

    导入Relation

    use Illuminate\Database\Eloquent\Relations\Relation;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 2021-09-08
      • 2018-06-19
      • 2019-01-12
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多