Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

php - Synchronizing a one-to-many relationship in Laravel

If I have a many-to-many relationship it's super easy to update the relationship with its sync method.

But what would I use to synchronize a one-to-many relationship?

  • table posts: id, name
  • table links: id, name, post_id

Here, each Post can have multiple Links.

I'd like to synchronize the links associated with a specific post in the database, against an inputted collection of links (for example, from a CRUD form where I can add, remove, and modify links).

Links in the database that aren't present in my input collection should be removed. Links that exist in the database and in my input should be updated to reflect the input, and links that are only present in my input should be added as new records in the database.

To summarize the desired behavior:

  • inputArray = true / db = false ---CREATE
  • inputArray = false / db = true ---DELETE
  • inputArray = true / db = true ----UPDATE
question from:https://stackoverflow.com/questions/27204485/synchronizing-a-one-to-many-relationship-in-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately there is no sync method for one-to-many relations. It's pretty simple to do it by yourself. At least if you don't have any foreign key referencing links. Because then you can simple delete the rows and insert them all again.

$links = array(
    new Link(),
    new Link()
);

$post->links()->delete();
$post->links()->saveMany($links);

If you really need to update existing one (for whatever reason) you need to do exactly what you described in your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...