有两种型号:
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])
);
}
}
但是当用户尝试编辑产品时,用户可能会删除现有图片并尝试添加新图片并发送表单。我应该采用哪种方式来更新图像关系。我应该删除与产品相关的所有图像并创建新图像吗?对我来说这看起来不好,有什么最好的吗?
答案 0 :(得分:1)
首先,你的关系是错误的我认为你与产品和形象有一对多关系
所以这应该是
public function images(){
return $this->hasMany('product_image');
}
public function product()
{
return $this->belongsTo(Product::class);//import your product class with use
}
你也错误地定义了你的关系。在您的关系中,您将在某些情况下定义该类,您可以传递外键,本地键和表名称请参阅Defining Relationships
这应该是
public function images(){
return $this->hasMany('product_image');
}
public function brand(){
return $this->belongsTo('brand');
}
此
public function images(){
return $this->hasMany(Product_Image::class);//import class
}
public function brand(){
return $this->belongsTo(Brand::class);//import Brand class
}
此外,您可以在此处简化代码
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])
);
}
$product->images()->save(
new Product_Image(['image' => $v,'main' => (int)($data['main'] == $k)])
);