hasOne 关系在 laravel 中不起作用
hasOne Relation not working in laravel
你好,我想建立两个表之间的关系,首先 Table 是 product,其次是 productimages
ProductController.php
public function product(){
$products = Product::all();
dd($products->images);
}
Product.php(模态)
class Product extends Model
{
public $timestamps = false;
//
public function images()
{
return $this->hasOne(ProductImage::class);
}
}
ProductImage.php(型号)
class ProductImage extends Model
{
public function product(){
return $this->belongsTo(Product::class);
}
}
当我使用此方法时 $products = Product::find(1);
工作找到但我需要所有。
谢谢
当您执行 $products->images
时,您正在尝试访问 collection 的 属性。
使用 with()
方法预加载所有产品及其图像:
$products = Product::with('images')->get();
然后你就可以得到每个产品的图像并避免N + 1问题:
@foreach ($products as $product)
// Access $product->image here
@endforeach
Product::with('images')->get();
你好,我想建立两个表之间的关系,首先 Table 是 product,其次是 productimages
ProductController.php
public function product(){
$products = Product::all();
dd($products->images);
}
Product.php(模态)
class Product extends Model
{
public $timestamps = false;
//
public function images()
{
return $this->hasOne(ProductImage::class);
}
}
ProductImage.php(型号)
class ProductImage extends Model
{
public function product(){
return $this->belongsTo(Product::class);
}
}
当我使用此方法时 $products = Product::find(1);
工作找到但我需要所有。
谢谢
当您执行 $products->images
时,您正在尝试访问 collection 的 属性。
使用 with()
方法预加载所有产品及其图像:
$products = Product::with('images')->get();
然后你就可以得到每个产品的图像并避免N + 1问题:
@foreach ($products as $product)
// Access $product->image here
@endforeach
Product::with('images')->get();