laravel - 获取没有电子邮件列的用户
问题描述
我有一个数据库,可以从中获取有关作者的评论和数据。
我和评论的作者一起使用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',
];
解决方案
您可以指定您在急切加载时选择的哪些列,如下所示:
Comment::with(['author'=>function($query){
$query->select('name','avatar');
}])->get();
或者简单地说:
Comment::with('author:name,avatar')->get()
推荐阅读
- voltdb - 在 voltdb Adhoc 存储过程中将多个参数作为数组传递时出错
- logging - 仅适用于企业应用程序和本地的中央日志记录解决方案
- python - Python 将列表 1 [I] 与列表 2 [i] 连接
- javascript - 我无法在 jQuery 中更改 HTML
- intel-fpga - 如何让 DE0-nano 使用 ttl-232R-3V3 电缆与 PC 进行 1 位通信(使用冲突语言)?
- r - 如何计算data.frame中日期间隔的总和?
- c++ - 在通知条件变量之前添加一个空的锁定范围会防止丢失通知吗?
- java - MockBean 未注入 MVC 控制器测试
- kentico - Kentico:10 如何同时允许 E-Mail 和 Username 认证
- scala - 如何使用Scala将值保存在文件中