将 Laravel with() Json 数组移动到父 Json 数组
Move Laravel with() Json array to parent Json array
我正在使用此代码获取数据。
$user = User::where('active', 1)->with(['spots:spot_name,spot_uid'])->get();
效果很好!它获取关系并输出数据。
然而数据看起来是这样的。
user_uid: 5
spots: {spot_name: 'backend'}
description: "Test user works in helpdesk"
department: "9"
它显示了我需要的所有数据,但我希望 spot_name 不在其自己的子 json 数组中,而只是让spot_name成为点。像这样:
spots: "backend"
我知道这是因为它获得了2列,然后我隐藏了1列。
这是不可能的,还是我只是走错了路?任何信息都会很棒。
您可以使用集合格式化输出:
$user->map(function ($x) {
$arr = $x->toArray();
$arr['spots'] = $arr['spots'][0]['spot_name'];
return $arr;
});
然后退出这个用户。
你可以的
User::where('active', 1)->withCount(['spots as spot_name' => function ($q) {
$q->select('spot_name');
}]);
输出
{
...
spot_name: 'backend'
}
我正在使用此代码获取数据。
$user = User::where('active', 1)->with(['spots:spot_name,spot_uid'])->get();
效果很好!它获取关系并输出数据。
然而数据看起来是这样的。
user_uid: 5
spots: {spot_name: 'backend'}
description: "Test user works in helpdesk"
department: "9"
它显示了我需要的所有数据,但我希望 spot_name 不在其自己的子 json 数组中,而只是让spot_name成为点。像这样:
spots: "backend"
我知道这是因为它获得了2列,然后我隐藏了1列。
这是不可能的,还是我只是走错了路?任何信息都会很棒。
您可以使用集合格式化输出:
$user->map(function ($x) {
$arr = $x->toArray();
$arr['spots'] = $arr['spots'][0]['spot_name'];
return $arr;
});
然后退出这个用户。
你可以的
User::where('active', 1)->withCount(['spots as spot_name' => function ($q) {
$q->select('spot_name');
}]);
输出
{
...
spot_name: 'backend'
}