【问题标题】:laravel - How can I get the user information of each commentlaravel - 如何获取每条评论的用户信息
【发布时间】:2018-06-01 11:08:41
【问题描述】:

我有这些模型:

class Post extends Model
{
    protected $primaryKey = 'post_id';
    public function comments()
    {
        return $this->hasMany(Comment::class, 'post_id', 'post_id');
    }
}

class Comment extends Model
{
    protected $primaryKey = 'comment_id';

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }
}

class User extends Authenticatable
{
    protected $primaryKey = 'user_id';
    public function comments()
    {
        return $this->hasMany(Comment::class, 'user_id', 'commenter_id');
    }
}

class MyController extends Controller
{
    public function post($id = null)
    {
        $post = Post::where('post_id', $id)->first();
        $comments = $post->comments;
    }
}

我想要的是让每条评论的用户都像$post->comments->user 这样简单地获取用户信息,如下所示:

@foreach($post->comments as $comment)
    {{ $comment->user->first_name.' '.$comment->user->last_name }}
@endforeach

我该怎么做?我想我需要一个名为 hasManyThrough 的东西,但它太复杂了,我很困惑:|

【问题讨论】:

    标签: php laravel model


    【解决方案1】:

    是的,您可以使用评论对象获取用户对象,使用

    $post = Post::with('comments.user')->where('post_id', $id)->first();
    

    并在 cmets 模型中为用户定义映射

    class Comment extends Model
    {
        protected $primaryKey = 'comment_id';
    
        public function post()
        {
            return $this->belongsTo(Post::class, 'post_id');
        }
    
        public function user()
        {
            return $this->belongsTo(User::class, 'user_id');
        }
    }
    

    【讨论】:

    • 当我想用$comments = $post->comments->user; 得到结果时,它会抛出错误Property [user] does not exist on this collection instance.
    • @kodfire 你需要遍历你的 cmets,然后在每个评论对象上你可以访问用户对象,你不能访问 cmets 集合上的用户对象
    • 非常感谢@MKhalidJunaid 顺便问一下,如果我的查询中不包含with('comments.user') 怎么办?
    • with() 基本上是为了在您的情况下急切加载,如果您正在循环数据,那么您不需要这个
    • @MKhalidJunaid 他不需要它,但如果他循环,他将为每条评论执行一个查询,所以我会说他确实需要它来提高性能
    【解决方案2】:

    只需在您的 Comment 模型中创建函数,该函数必须返回这样的关系

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
    

    然后在你的评论对象上调用这个函数

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多