我有两张桌子。 1.products 2.product_images。
产品领域表:id,product_name,created_at,updated_at
product_images字段表:id,product_id,product_image,created_at,updated_at
products表与product_images表具有OnetoMany关系。
所以在我定义的产品模型中:
public function productImage()
{
return $this->hasMany(Product_image::class,'product_id');
}
现在我想从两个表中获取产品ID 1的所有数据。
所以我在下面有这个代码:
应用\产品::发现(1) - > productImage
结果集是:
Illuminate\Database\Eloquent\Collection {#689
all: [
App\Product_image {#679
id: 1,
product_id: 1,
product_image: "1494787942_download (1).jpg",
created_at: "2017-05-14 18:52:22",
updated_at: "2017-05-14 18:52:22",
},
],
}
但我没有得到product_name。解决方案是什么? 感谢。
答案 0 :(得分:0)
productImage
没有product_name
属性,但product
属性。当您显示App\Product::find(1)->productImage;
的结果时,您不能指望它显示product_name
属性。
如果您想查看product
及其附加图片,请执行以下操作:
$product = \App\Product::with(["productImage"])->find(1);
然后,执行dd($product)
会向您显示product
(包括product_name
属性)和productImage
作为返回Collection
的属性的属性productImage
条记录。
请记住,使用名为productImage
的函数返回多个productImage
记录会产生误导;命名惯例会建议productImages()
。