[英]How to update multiple rows and database with same value at once? Laravel
I'm stuck in code. 我陷入了代码困境。 I managed to create a form that adds a multiple number of rows in db but I do not know how to update them at the same time when i need to use product_code as id.
我设法创建一个在db中添加多个行的表单,但是当我需要使用product_code作为id时,我不知道如何同时更新它们。
This is table 1 (products) structure: 这是表1(产品)结构:
id | product_name | product_code
1 | Name1 | 101
2 | Name2 | 102
3 | Name3 | 103
4 | Name4 | 104
This is table 2 (products_ing) structure: 这是表2(products_ing)结构:
id | product_code | ing_name | ing_weight 1 | 101 | INGName1 | 110 2 | 101 | INGName2 | 10 3 | 101 | INGName3 | 54 4 | 101 | INGName4 | 248
This is edit function: 这是编辑功能:
public function post_edit($id = null)
{
if(Input::get('submit'))
{
// ID
if($id !== null)
{
$id = trim(filter_var($id, FILTER_SANITIZE_NUMBER_INT));
}
$input = Input::all();
$validation = Validator::make($input);
else
{
foreach ($input as $key => $value)
{
$input[$key] = ($value !== '') ? trim(filter_var($value, FILTER_SANITIZE_STRING)) : null;
}
try
{
DB::table('products')
->whereIn($id)
->update(array(
'product_name' => $items['product_name'],
'product_code' => $items['product_code']
));
}
}
return $this->get_edit($id);
}
With this I can only edit *product_name* and product_code from products table by id. 有了这个,我只能通过id编辑产品表中的* product_name *和product_code 。 But I'm trying to update multiple rows from db with same product_code that would serve as id.
但我正在尝试使用相同的product_code更新db中的多行,这些行将用作id。
// I found on Google images one good image that explains what I'm trying to do but with Laravel: //我在Google图片上找到了一个很好的图像,它解释了我正在尝试做的事情,但是使用Laravel:
Is there a solution? 有解决方案吗? Thank you in advance!
先感谢您!
Assuming you are using MySQL: Let the database's foreign key
do this for you, with the ON UPDATE CASCADE command. 假设您正在使用MySQL:让数据库的
foreign key
使用ON UPDATE CASCADE命令为您执行此操作。 This will update all referenced tables if you change the product_code
in your base products
table. 如果更改基本
products
表中的product_code
,这将更新所有引用的表。
CREATE-Script of products_ing
CREATE-
products_ing
脚本_ing
...
product_code INT NOT NULL REFERENCES products(product_code) ON UPDATE CASCADE
...
As laravel migration
作为laravel
migration
Schema::create('products_ing', function($table) {
$table->increments('id');
$table->int('product_code');
$table->string('ing_name');
$table->int('ing_weight');
/* All the other key stuff */
$table
->foreign('product_code')
->references('product_code')
->on('products')
->onUpdate('cascade');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.