Search code examples
laraveleloquentlaravel-9laravel-query-builder

how to update key/value database with laravel?


I'm just learning laravel. I want update key / value in database with laravel api but not work.

My products model is one to many with ProductMeta and many to many with contents model.

My Models

class Product extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function productMeta()
    {
        return $this->hasMany(ProductMeta::class);
    }

    public function content()
    {
        return  $this->belongsToMany(Content::class, 'product_contents')->withTimestamps();
    }
}
class ProductMeta extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function products()
    {
        return $this->belongsTo(Product::class);
    }
}
class Content extends Model
{
    use HasFactory;

    protected $guarded= [];

    public function product()
    {
        return $this->belongsToMany(Product::class, 'product_contents');
    }

Controller

public function update(Request $request, $id)
{
    $product = Product::findOrFail($id);

     DB::table('product_metas')
        ->upsert(
            [
                [
                    'product_id' => $product->id,
                    'key' => 'name',
                    'value' => $request->name,
                ],
                [
                    'product_id' => $product->id,
                    'key' => 'price',
                    'value' => $request->name,
                ],
                [
                    'product_id' => $product->id,
                    'key' => 'amount',
                    'value' => $request->name,
                ],
            ],
            ['product_id','key'],
            ['value']
        );

    return \response()->json([], 204);
}

Table Structure

databasee

API parameter

Postman

I tried with update and updateOrcreate and updateOrInsert and upsert methods.

just in upsert method writed database but inserted new data.not updated.

database 2


Solution

  • my problem solved this way:

    
        ProductMeta::query()->where('product_id', $id)->upsert([
        ['product_id' => $id, 'key' => 'name', 'value' => $request->name],
        ['product_id' => $id, 'key' => 'price', 'value' => $request->price],
        ['product_id' => $id, 'key' => 'amount', 'value' => $request->amount]],
        ['product_id'], ['value']);
        
        $contentRecord = Product::find($id);
        $contentRecord->content()->update(['path'=>$request->path]);
                    
            return response()->json([], 204);
    
    

    I forget use query() method for ProductMeta and added $table->unique(['product_id', 'key']); to product meta migration.

    **products relation one to many with product Meta And Many to many with content.