2017-08-19 14 views
1

まあ、私はLaravel 5.4を使用しており、1対多の(hasMany)リレーションシップを更新する必要がある状況に達しました。 私はproductsテーブルとproduct_imagesテーブルを持っています。以下は各モデルの私の関係の定義です。Laravel 5の1対多の(hasMany)リレーションを更新する方法

//Product.php 
public function productImages() 
{ 
    return $this->hasMany('App\ProductImage'); 
} 

//ProductImage.php 
public function product() 
{ 
    return $this->belongsTo('App\Product'); 
} 

既存の製品を更新するためのフォームインターフェイスを提供しています。その中に私は4つのオプションのファイルアップロードのHTMLタグを更新したり、製品の画像を追加したりしています。これら4つの画像のアップロードはすべてオプションであることを忘れないでください

だから私の質問は

  • 提供されている場合product_imagesテーブル
    1. 更新、既存のエントリへの最善のアプローチ(laravel方法は)それは
    削除された場合は、既存の削除、新しいものを追加しているものです

    私はattachまたはdetachの方法(sync)を知っていて、すべてを削除してから提供されたものを追加します。しかし、既存のイメージを置き換える場合はidを維持したい。

  • 答えて

    0

    私は公式Laravelのページや他の多くのサイトに十分なドキュメントがあると思う...しかし、ここで多くのアプローチの一つである:

    1.Update

    $id = $request->product_id; 
    $path = 'path'; 
    $product = Product::where('id', $id)->with('productImages')->first(); 
    //For updating all the records that belong to the given product 
    foreach($product->productImages as $productImage){ 
        $productImage->path = $path; 
        $productImage->save(); 
    } 
    //You can also load a single model like this: 
    //$productImages = ProductImages::find($product_image_id); 
    //And then update 
    //$productImages->path = $path; 
    //$productImages->save(); 
    

    2は、新しいものを追加します。

    $productImages = new ProductImage; 
    $productImages->path = 'path'; 
    $productImages->product_id = $id; 
    $productImages->save(); 
    
    $id = $request->id; 
    $productImages = ProductImages::find($id); 
    $productImages->delete(); 
    
    を削除します。
    関連する問題