【发布时间】:2020-11-12 05:21:30
【问题描述】:
我有这样的表
products - id, name, description, category_id, brand_id, color_id, material_id, price
extras - id, product_id, size_id, stock
images - id, product_id, name, path
size - id, name
模型产品:
public function extra()
{
return $this->hasMany('App\Extra', 'product_id', 'id');
}
public function image()
{
return $this->hasMany('App\Image', 'product_id', 'id');
}
模型额外:
public function size()
{
return $this->hasOne('App\Size', 'id', 'size_id');
}
public function product()
{
return $this->belongTo('App\Product', 'product_id', 'id');
}
模型图片:
public function product()
{
return $this->belongsTo('App\Product', 'product_id', 'id');
}
如何从 extras 和 images 表中获取尺寸名称、图像名称和路径值? 我可以使用此查询 echo $product['extra'][0]['size']['name']; 获取尺寸名称,但我只得到一个我不知道的值如何循环获取所有值。
$products = Product::with(['brand', 'category', 'color', 'image', 'material', 'extra', 'user'])->get();
foreach ($products as $product)
{
echo $product['name'] ." ". strip_tags($product['description']) ." ". $product['category']['name'] ." ". $product['brand']['name'] ." ". $product['color']['name'] ." ". $product['material']['name'] ." ". $product['price'] ." ". $product['sku'] ." ". $product['user']['name'] ."</br>";
echo $product['extra'][0]['size']['name'];
}
有什么建议我需要做什么或我可以阅读以解决这个问题吗?谢谢。
【问题讨论】:
标签: laravel eloquent relationship