laravel - 在laravel中检索外键第一个值
问题描述
我有三个表产品、类别和图像。Category 和 Image 表与 Product 表有关系。当我使用$all_product = Product::with('category','image')->get();
产品信息类别信息和图像信息成功显示我想要的是问题:如何检索图像数组的第一个值?
"all_objects": [
{
"id": 1,
"name": "samsung",
"price": "2000",
"category_id": 1,
"created_at": "2020-02-17 13:27:24",
"updated_at": "2020-02-17 13:27:24",
"category": {
"id": 1,
"category_name": "android",
"created_at": "2020-02-17 13:26:42",
"updated_at": "2020-02-17 13:26:42"
},
"image": [
{
"id": 1,
"image_name": "image_787.jpeg",
"product_id": 1,
"created_at": "2020-02-17 13:27:25",
"updated_at": "2020-02-17 13:27:25"
},
{
"id": 2,
"image_name": "image_539.jpeg",
"product_id": 1,
"created_at": "2020-02-17 13:27:25",
"updated_at": "2020-02-17 13:27:25"
},
{
"id": 3,
"image_name": "image_606.jpeg",
"product_id": 1,
"created_at": "2020-02-17 13:27:25",
"updated_at": "2020-02-17 13:27:25"
},
{
"id": 4,
"image_name": "image_102.jpeg",
"product_id": 1,
"created_at": "2020-02-17 13:27:26",
"updated_at": "2020-02-17 13:27:26"
}
]
},
解决方案
尝试这个:
$all_product = App\Product::with(['category','image' => function ($query) {
$query->first();
}])->get();
请参阅约束急切负载
推荐阅读
- vue.js - Vue:如何更改状态值并在其他页面中使用它并在启动时更改页面结构?
- c++ - 如何使用 PBC 库?
- google-cloud-platform - 在 Google Cloud Vertex AI 上使用客户处理程序进行部署
- c++ - FFMPEG 错误:解码 H.265 流时“帧中的第一个片段丢失”
- typescript - 在 React Native 中,如何从主项目中更改本地库,而无需编译前者
- php - 就像 PHP 中选择的文件名一样
- javascript - JS自定义元素,我如何获取属性值
- osgi - SpringToolSuite 4 和适当的 OSGi 清理
- scala - 带有值列表的 Scala Futures 用于理解
- typescript - 在使用 React Native 测试和 TypeScript 时传递道具