Laravel 5.8:MorphMany关系返回空

时间:2019-09-04 16:59:31

标签: php laravel laravel-5 eloquent relationship

评论模型:

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

public function comments()
{
    return $this->hasMany(Comment::class , 'parent_id' , 'id');
}

public function setCommentAttribute($value)
{
    $this->attributes['comment'] = str_replace(PHP_EOL , "<br>" , $value);
}

发布模型:

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

控制器:

public function show_comments(Post $post)
{
    $comments = $post->comments()
                ->where('approved' , 1)
                ->where('parent_id', 0)
                ->latest()
                ->with(['comments' => function($query) {
                    $query->where('approved' , 1)->latest();
                }])->get();

    dd($comments);
    return view('post',compact('comments'));
}

数据库表注释:

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('parent_id')->unsigned()->default(0);
            $table->boolean('approved')->default(0);
            $table->text('comment');
            $table->integer('commentable_id')->unsigned();
            $table->string('commentable_type');
            $table->timestamps();
        });

$dd($comments)返回#items: []或为空。有数据库记录,我可以使用其他方法访问它们。

我问过很多次,但是没有运气。

1 个答案:

答案 0 :(得分:1)

我试图解决同一问题几个小时。对于任何寻找答案的人:

检查commentable_type表中的comments字段是否包含格式正确的字符串

'commentable_type' => 'App/Models/Comment',       // Does not work

'commentable_type' => 'App\Models\Comment',      // Works ?