Laravel 仅在两列冲突时更新
Laravel upsert only if two columns conflict
我有以下table
id | invoice_id | position | item_name | qty
---|------------|----------|-----------|----
1 | 1234 | 200 | shaft | 2
2 | 1234 | 202 | spear | 1
3 | 1235 | 200 | shaft | 10
4 | 1235 | 202 | spear | 20
仅当 invoice_id
和 position
匹配时,我如何“定位”更新第一行(id
是 1
)?如果我为 1234 的 invoice_id
添加一个 position
500 的新项目,它会插入一个新行,否则如果 position
是 200 或 202,它会更新现有的(名称或数量)?
我看过 laravel 的 v8 upsert()
函数,但它只需要一个唯一标识列,在本例中不需要两个。
使用方法updateOrCreate()
。第一个参数是唯一性条件,第二个参数是属性的其余部分。这是 upsert()
的单行版本
Model::updateOrCreate(
['invoice_id' => '1234', 'position' => '500'],
['qty' => 5, 'item_name' => 'shaft']
);
upsert()
我不限于一个独特的列
Flight::upsert([
['invoice_id' => '1234', 'position' => '500', 'qty' => 5, 'item_name' => 'shaft'],
['invoice_id' => '1234', 'position' => '600', 'qty' => 10, 'item_name' => 'shaft']
], ['invoice_id', 'position'], ['qty']);
第一个参数用于条目,第二个参数用于标识列的列表,第三个参数用于更新的字段(如果找到匹配项)。
All databases systems except SQL Server require the columns in the second argument provided to the upsert method to have a "primary" or "unique" index.
为了能够使用 upsert
方法,您需要在由 invoice_id
和 position
[=20 组成的复合键上添加一个 unique
约束=]
我有以下table
id | invoice_id | position | item_name | qty
---|------------|----------|-----------|----
1 | 1234 | 200 | shaft | 2
2 | 1234 | 202 | spear | 1
3 | 1235 | 200 | shaft | 10
4 | 1235 | 202 | spear | 20
仅当 invoice_id
和 position
匹配时,我如何“定位”更新第一行(id
是 1
)?如果我为 1234 的 invoice_id
添加一个 position
500 的新项目,它会插入一个新行,否则如果 position
是 200 或 202,它会更新现有的(名称或数量)?
我看过 laravel 的 v8 upsert()
函数,但它只需要一个唯一标识列,在本例中不需要两个。
使用方法updateOrCreate()
。第一个参数是唯一性条件,第二个参数是属性的其余部分。这是 upsert()
Model::updateOrCreate(
['invoice_id' => '1234', 'position' => '500'],
['qty' => 5, 'item_name' => 'shaft']
);
upsert()
我不限于一个独特的列
Flight::upsert([
['invoice_id' => '1234', 'position' => '500', 'qty' => 5, 'item_name' => 'shaft'],
['invoice_id' => '1234', 'position' => '600', 'qty' => 10, 'item_name' => 'shaft']
], ['invoice_id', 'position'], ['qty']);
第一个参数用于条目,第二个参数用于标识列的列表,第三个参数用于更新的字段(如果找到匹配项)。
All databases systems except SQL Server require the columns in the second argument provided to the upsert method to have a "primary" or "unique" index.
为了能够使用 upsert
方法,您需要在由 invoice_id
和 position
[=20 组成的复合键上添加一个 unique
约束=]