Home > Net >  how to update key/value database with laravel?
how to update key/value database with laravel?

Time:01-30

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

CodePudding user response:

In Laravel, you can update records in a database using the Eloquent ORM. Here's a simple example of updating a record:

Get the record you want to update:

$record = ModelName::find($id);

Update the record's values:

$record->key = $value;
$record->save(); 

Alternatively, you can use the update method to update multiple values at once:

ModelName::where('id', $id)->update(['key' => $value]);

CodePudding user response:

In your case, you already find out data model in controller, so you can just upsert using your $product model like this.

$product = Product::findOrFail($id);
$product->upsert($data);

In addition your problem is your table name is not matching with your structure table name. In your controller DB::table('product_metas') should be DB::table('products_meta').

  • Related