2015-09-03 65 views
0

有2種型號:如何更新Laravel關係的表

ProductProduct_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]) 
     ); 
    } 
} 

但是當用戶嘗試編輯產品,用戶可能會刪除現有圖像並嘗試添加新圖像併發送表單。我應該遵循哪種方式來更新圖像關係。我應該刪除與產品相關的所有圖像並創建新圖像嗎?這對我來說看起來很不好,對此有沒有最好的?

回答

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)]) 
     ); 
+0

謝謝!我應用了你的修改,並從中學到了一些好東西。我仍然不知道如何更新與產品相關的圖像。我應該刪除所有圖像並從表單中添加新圖像嗎? –