laravel - Laravel 从关系中只得到一列
问题描述
我有一个表 user_childrens,其中包含 id_parent 和 id_user。我试图用这个列出父母的所有孩子:
代码:
//relation in model via belongsTo
$idparent = auth('api')->user()->id;
$list = UserChildren::where('id_parent',$idparent)
->with('child:id,name,email')
->get();
return $list->toJson();
回报是:
[
{
"id": 1,
"id_parent": 1,
"id_user": 1,
"created_at": null,
"updated_at": null,
"child": {
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel@example.com"
}
},
{
"id": 4,
"id_parent": 1,
"id_user": 2,
"created_at": null,
"updated_at": null,
"child": {
"id": 2,
"name": "Krystel Lehner",
"email": "cernser@example.net"
}
}
]
但它是 API,所以我只想要子列,例如:
[
{
"id": 1,
"name": "Mr. Davin Conroy Sr.",
"email": "prempel@example.com"
},
{..}
]
用户儿童模型:
public function child() {
return $this->belongsTo('App\User','id_user','id');
}
我知道我可以通过集合上的 .map() 来做到这一点,但也许这个查询中已经有其他解决方案
解决方案
您可以使用此代码
$idparent = auth('api')->user()->id;
$childs = User::whereHas('user_childrens', function ($query) use ($idparent) {
$query->where('id_parent', $idparent);
})->get(['id', 'name', 'email']);
dd($childs->toJson());
和用户模型定义user_childrens
关系。
public function user_childrens()
{
return $this->hasMany('App\UserChildren','id_user','id');
}
另请参阅文档https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence
推荐阅读
- javascript - 为什么我的“更改”事件没有按预期工作?
- ssl - influxdb 2.0 证书验证失败:证书已过期 (_ssl.c:1129)
- angular - 使用外部服务器端后端设置 Angular
- reactjs - 如何处理来自 supabase 登录的重定向?
- revit-api - 在 Linked with Revit API 中创建 ViewSet
- r - 在 R Shiny 中,重新渲染矩阵时如何在扩展输入矩阵中保留值?
- maven - Maven:可以使用不同的参数执行相同的执行
- google-bigquery - 如果您想在 BigQuery 中为每个代理机构分离可用数据怎么办?
- java - 如何将拦截器添加到 WebSocket
- laravel - 如何使用 php 在谷歌云上提取 zip 文件