Sync Update Pivot (syncWithPivotValues) in Laravel 9

Ta hay thường dùng viết mối quan hệ Many-to-Many và có các cột được tạo mới trong bảng table được phát sinh ra. Vậy làm sao ta có thể thêm giá trị cho các cột được thêm và update nó

VD:

# Product Model: Mình có tạo các cột mới bổ sung vào table "product_language" (title,keyword,description,slug,body)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    use HasFactory;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
      
        'category_id',
        'price',
        'images',
        'user_id'
    ];
  
    public function languages(){
        return $this->belongsToMany("App\Models\Language","product_language","product_id","language_id")->withPivot('title','slug', 'keyword', 'description', 'body')
        ->withTimestamps();;

    }
 

}

# Language Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Language extends Model
{
    use HasFactory;

    public function products(){
        return $this->belongsToMany('App\Models\Product','product_language','product_id','language_id');

    }
}

Để thêm giá trị vào các cột trong pivot thì chúng ta có thể dụng cách sau:

/* set language */
        if (count($request->lang) > 0)
            $languages = Language::whereIn("code", $request->lang)->get();
        else
            $languages = Language::where("code", app()->getLocale())->get();
        $product->languages()->attach($languages, $request->only(['title','slug', 'keyword', 'description', 'body']));
/* end set language */

Bạn xem ở chổ attach array thứ 2 ta cần đưa vào các giá trị được khai báo trong Product model bên trên

Còn bạn muốn update các pivot thì các bạn sử dụng phương thức syncWithPivotValues 

  /* set language */
   $languages = Language::where("code", $request->lang)->first();
    $product->languages()->syncWithPivotValues($languages, $request->only(['title', 'slug','keyword', 'description', 'body']),false);
 /* end set language */

Đoạn code trên nó kiểm tra xem, đã có dữ liệu trong bảng table product_language chưa.  Nếu chưa có ,nó sẽ thêm vào. Còn có rồi nó sẽ update lại giá trị đó

 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)