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
API parameter
I tried with update
and updateOrcreate
and updateOrInsert
and upsert
methods.
just in upsert method writed database but inserted new data.not updated.
2
Answers
my problem solved this way:
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.
In your case, you should use
updateOrCreate()
instead ofupsert
.or
In addition your problem is your table name is not matching with your structure table name. In your controller
DB::table('product_metas')
should beDB::table('products_meta')
.