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])
);
}
}
但是當用戶嘗試編輯產品,用戶可能會刪除現有圖像並嘗試添加新圖像併發送表單。我應該遵循哪種方式來更新圖像關係。我應該刪除與產品相關的所有圖像並創建新圖像嗎?這對我來說看起來很不好,對此有沒有最好的?
謝謝!我應用了你的修改,並從中學到了一些好東西。我仍然不知道如何更新與產品相關的圖像。我應該刪除所有圖像並從表單中添加新圖像嗎? –