laravel - 使用用户表中的用户和变形表中的用户图像从评论表中获取所有评论?
问题描述
我有三个模型:'Post'、'User'、'Comment'、'Image'。模型“评论”和“图像”具有多态关系“现在我想获取带有评论者用户图像的帖子的所有评论。谁能帮我解决它?我的英语不好,所以如果需要澄清,请随时问我
解决方案
假设您有以下模型和关系:
class Post extends Model
{
public function comments()
{
return $this->mophMany(Comment::class, 'commentable');
}
}
class Comment extends Model
{
public function author()
{
// I assume that the comments table has a user_id field.
return $this->belongsTo(User::class);
}
}
class User extends Authenticatable
{
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
}
然后,您可以通过以下方式获取具有所有嵌套关系的帖子:
return $post->load('comments.author.image');