[英]Laravel 5.7 eloquent update/delete multiple records
My table structure is like this: 我的表结构是这样的:
invoices:
id, title, desciption, total_amount, --
products:
id, name, price, --
invoice_products
id, invoice_id, product_id, --
One invoice can have multiple products, so, 一个发票可以有多个产品,因此,
I created an invoice with products, then data fills according to above DB structure. 我创建了带有产品的发票,然后根据上述数据库结构填充数据。
When i update invoice (let say invoice_id = 2 ), then, i am confused what is the best way to update "invoice_products" table. 当我更新发票(比如说invoice_id = 2)时,我感到困惑的是更新“ invoice_products”表的最佳方法是什么。
My approach is ( for "invoice_products" table): 我的方法是(用于“ invoice_products”表):
I think this is not good approach, as i am force deleting the rows in "invoice_products" and again inserting new updated products. 我认为这不是一个好方法,因为我被迫删除“ invoice_products”中的行,然后再次插入新的更新产品。
is there any way to do via eloquent ? 有什么办法可以通过雄辩来做?
I think invoice_products is pivot table. 我认为invoice_products是数据透视表。 You should use sync method. 您应该使用同步方法。
$productIds = [1,2,3];
$Invoice->products()->sync($productIds);
Also in your invoice Model the relationship should be like this 同样在您的发票模型中,关系应如下所示
public function products()
{
return $this->belongsToMany(Invoice::class, 'invoice_products', 'invoice_id', 'product_id');
}
You can use Laravel many to many relation to achieve this functionality: 您可以使用Laravel多对多关系来实现此功能:
Invoice Model 发票模型
public function products()
{
return $this->belongsToMany('App\Product', 'invoice_products');
}
Product Model 产品型号
Though it is not required here but you can use this to get invoice for related products. 虽然这里不是必需的,但是您可以使用它来获取相关产品的发票。
public function invoices()
{
return $this->belongsToMany('App\Product', 'invoice_products');
}
To update the existing data you can use sync
method: 要更新现有数据,可以使用sync
方法:
$products = [1, 2, 3, 4];
$invoice->products()->sync($products);
You can read more about relationship over https://laravel.com/docs/5.7/eloquent-relationships 您可以通过https://laravel.com/docs/5.7/eloquent-relationships阅读有关关系的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.