评论模型:
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: []
或为空。有数据库记录,我可以使用其他方法访问它们。
我问过很多次,但是没有运气。
答案 0 :(得分:1)
我试图解决同一问题几个小时。对于任何寻找答案的人:
检查commentable_type
表中的comments
字段是否包含格式正确的字符串
'commentable_type' => 'App/Models/Comment', // Does not work
'commentable_type' => 'App\Models\Comment', // Works ?