php - Laravel 使用关系从 Query 中的 Array 获取单个项目
问题描述
在我的一个模型中,例如posts
我有一个列数组featured_image
,当我从这个模型获取返回所有这些数组项的结果查询时,例如:
"featured_image": {
"images": {
"original": "/uploads/post_images/2020/1598873165.jpg",
"300": "/uploads/post_images/2020/300_1598873165.jpg",
"900": "/uploads/post_images/2020/900_1598873165.jpg"
},
"thumbnail": "/uploads/post_images/2020/300_1598873165.jpg"
},
现在我如何修改下面的查询以从这个数组中只获取一个项目,例如thumbnail
?
public function allData()
{
$posts = Post::with(['groups', 'categories' => function ($query) {
$query->whereLocked(false);
}])->wherePublished(true)->get();
return response()->json([
'posts' => $posts,
], 200);
}
解决方案
你可以试试这个:
public function allData()
{
$posts = Post::with(['groups', 'categories' => function ($query) {
$query->whereLocked(false);
}])->wherePublished(true)
->select('{primary must included to use With}', 'other', 'columns', 'featured_image->thumbnail as thumbnail')
->get();
return response()->json([
'posts' => $posts,
], 200);
}
推荐阅读
- windows - 无法卸载新更新 KB:4489881 (Windows 8.1)
- javascript - 在 LARAVEL 中使用 JS 数组通过 AJAX 将 HTML 动态插入视图
- python - postgresql auth django(用户“BlogAdmin2”的密码验证失败)
- javascript - 属性“cacheLocation”的类型不兼容
- scala - 用先前的字段值填充 DataFrame 中的空白字段
- c# - Xamarin ADAL AcquireTokenAsync 不返回结果!OnActivityResult 被击中
- batch-file - 是否可以使用批处理隐藏 Windows 复制文件窗口?
- wordpress - 如何找出父主题的 style.css $handle
- angular - 如何从常规打字稿类(非组件)调用角度 2+ 服务
- reactjs - 如何摆脱“必须使用重组道具”作业