0
有2种型号:如何更新Laravel关系的表
Product
和Product_Images
class Product extends Eloquent {
protected $guarded = [];
public $timestamps = true;
public function images(){
return $this->hasMany('product_image');
}
public function brand(){
return $this->belongsTo('brand');
}
}
class Product_Image extends Eloquent {
protected $table = 'product_images';
protected $guarded = [];
public function images(){
return $this->hasMany('product_image');
}
}
我可以做的更新或插入数据,这款车型
$product = new Product;
$product->title = $data['title'];
$product->alias = $data['alias'];
$product->short_description = $data['short_description'];
$product->price = $data['price'];
$product->brand_id = $data['brand_id'];
$product->description = $data['description'];
$product->published = 1;
$product->save();
foreach($data['images'] as $k => $v){
if($data['main'] == $k){
$product->images()->save(
new Product_Image(['image' => $v,'main' => 1])
);
}else{
$product->images()->save(
new Product_Image(['image' => $v,'main' => 0])
);
}
}
但是当用户尝试编辑产品,用户可能会删除现有图像并尝试添加新图像并发送表单。我应该遵循哪种方式来更新图像关系。我应该删除与产品相关的所有图像并创建新图像吗?这对我来说看起来很不好,对此有没有最好的?
谢谢!我应用了你的修改,并从中学到了一些好东西。我仍然不知道如何更新与产品相关的图像。我应该删除所有图像并从表单中添加新图像吗? –