【发布时间】:2021-08-17 16:41:08
【问题描述】:
我对基本的 laravel ORM 模型有疑问。我正在调用image 模型来获取每个product 的图像文件名(product 模型具有image_id 值)所以我从数据库中获取products 并使用foreach 循环循环所有图像并添加文件名给每个product:
foreach($products as $product) {
$pimg = image::find($product->image_id)->first()->filename;
$product->imagefilename = $pimg;
}
问题是结果中的所有产品都在imagefilename(JSON 编码响应)中显示相同的文件名:
[
{
"id": 1,
"name": "dell-v3557",
"description": "this is dell v3557 ,this is description",
"short_description": "short description of dell v3557",
"category_id": 1,
"subcategory_id": 1,
"image_id": 1,
"store_id": 1,
"price": 2100,
"discount_price": 1800,
"count": 5,
"countries": "all",
"created_at": "2021-05-28T11:07:10.000000Z",
"updated_at": "2021-05-28T11:07:10.000000Z",
"imagefilename": "dell-v3557.png"
},
{
"id": 2,
"name": "gr5-2017",
"description": "this is gr5 2017 , lorem ipsum dolor , this is description",
"short_description": "short description of gr5",
"category_id": 1,
"subcategory_id": 1,
"image_id": 2,
"store_id": 1,
"price": 700,
"discount_price": 550,
"count": 2,
"countries": "all",
"created_at": "2021-05-28T11:07:10.000000Z",
"updated_at": "2021-05-28T11:07:10.000000Z",
"imagefilename": "dell-v3557.png"
},
{
"id": 3,
"name": "iphone 11 pro",
"description": "this is iphone 11 pro , lorem ipsum dolor , this is description",
"short_description": "short description of iphone 11 pro",
"category_id": 1,
"subcategory_id": 1,
"image_id": 4,
"store_id": 1,
"price": 1400,
"discount_price": null,
"count": 8,
"countries": "all",
"created_at": "2021-05-28T11:07:10.000000Z",
"updated_at": "2021-05-28T11:07:10.000000Z",
"imagefilename": "dell-v3557.png"
},
{
"id": 4,
"name": "macbook pro",
"description": "this is macbook pro , lorem ipsum dolor , this is description",
"short_description": "short description of macbook pro",
"category_id": 1,
"subcategory_id": 1,
"image_id": 5,
"store_id": 1,
"price": 1850,
"discount_price": 1700,
"count": 13,
"countries": "all",
"created_at": "2021-05-28T11:07:10.000000Z",
"updated_at": "2021-05-28T11:07:10.000000Z",
"imagefilename": "dell-v3557.png"
}
]
我还尝试在每个循环中使用[ $img = new image; ],以防多次使用同一模型出现问题,但没有运气,有什么建议吗?
【问题讨论】: