首页 > 解决方案 > 获取没有电子邮件列的用户

问题描述

我有一个数据库,可以从中获取有关作者的评论和数据。

我和评论的作者一起使用axios下载异步评论。

用户.php

public function comments() {
    return $this->hasMany('App\Comment');
}

评论.php

public function author()
{
    return $this->belongsTo('App\User', 'user_id');
}

评论控制器.php

public function fetch(Request $request)
{
    $comments = Comment::with('author')
        ->orderByDesc('id')
        ->get();
    return response($comments, 200);
}

我只想获取 comment.author.name 和 comment.author.avatar 。除了隐藏字段还有其他方法吗?我认为我将需要其他方法中的其他字段。

用户.php

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'email', 'password', 'remember_token',
];

标签: laravel

解决方案


您可以指定您在急切加载时选择的哪些列,如下所示:

Comment::with(['author'=>function($query){
    $query->select('name','avatar');
}])->get();

或者简单地说:

Comment::with('author:name,avatar')->get()

推荐阅读