简体   繁体   English

[Laravel 模型]存在特定重复数据时如何更新。 [拉维尔]

[英][Laravel model]How can I update when a specific duplicated data is existed. [Laravel]

I have a table.我有一张桌子。

Books
`id(PK),name, genre, publish_date(DATE_TIME)` 

I would like to make it update When a record with same genre and publish_date exists.当存在具有相同流派和 publish_date 的记录时,我想让它更新。

id(PK),name, genre, publish_date(DATE_TIME)

for example例如

1,iq84,fiction,2022-04-11 1,iq84,小说,2022-04-11

is existed.存在。

when 1q84,fiction,2022-04-11 is saved then 2,1q84,fiction,2022-04-11 is created.保存 1q84,fiction,2022-04-11 后,将创建 2,1q84,fiction,2022-04-11。

I would like to make it "1,1q84,fiction,2022-04-11"我想让它成为“1,1q84,fiction,2022-04-11”

How can I fix it?我该如何解决? How should I change the table structure?我应该如何更改表结构?

Save function保存 function

$book = new Book;
$book->name = "1q84";
$book->genre = 1;//fiction
$book->publish_date = '2022-04-01';
$book->save();
$bookStore = new bookStore;
$bookStore->bookId = $book->id;

You can use the updateOrCreate method.您可以使用updateOrCreate方法。 for your example you can do it like this:对于您的示例,您可以这样做:

Book::updateOrCreate(
    ['gener' => 1,'publish_date' => '2022-04-01'],
    ['name' => '1q84']
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM