简体   繁体   中英

[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.

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

for example

1,iq84,fiction,2022-04-11

is existed.

when 1q84,fiction,2022-04-11 is saved then 2,1q84,fiction,2022-04-11 is created.

I would like to make it "1,1q84,fiction,2022-04-11"

How can I fix it? How should I change the table structure?

Save 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. for your example you can do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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