【发布时间】:2015-09-03 09:49:21
【问题描述】:
有两种型号:
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])
);
}
}
但是当用户尝试编辑产品时,用户可能会删除现有图像并尝试添加新图像并发送表单。我应该按照哪种方式更新图像关系。我应该删除与产品相关的所有图像并创建新图像吗?这对我来说似乎是不好的做法,有什么最好的吗?
【问题讨论】:
标签: php laravel eloquent relationship