Laravel Eloquent - 附加与同步

Laravel Eloquent - Attach vs Sync(Laravel Eloquent - 附加与同步)
本文介绍了Laravel Eloquent - 附加与同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Laravel 4 的 Eloquent ORM 中的 attach()sync() 有什么区别?我试图环顾四周,但找不到任何东西!

解决方案

attach():

  • 在处理多对多关系时插入相关模型
  • 不需要数组参数

示例:

$user = User::find(1);$user->roles()->attach(1);

sync():

attach()方法类似,sync()方法用于附加相关模型.但是,主要区别在于:

  • sync() 接受要放在数据透视表上的 ID 数组
  • 其次,最重要的,如果数组中不存在模型,同步方法会从数据透视表中删除数据,并只将新项目插入数据透视表.

示例:

user_role

<前>id user_id role_id1 12 12 12 53 12 2

$user = User::find(12);$user->roles()->sync(array(1, 2, 3));

以上操作将删除:

<前>id user_id role_id2 12 5

然后将 role_id 3 插入到表中.

user_role 表

<前>id user_id role_id1 12 13 12 24 12 3

What is the difference between attach() and sync() in Laravel 4's Eloquent ORM? I've tried to look around but couldn't find anything!

解决方案

attach():

  • Insert related models when working with many-to-many relations
  • No array parameter is expected

Example:

$user = User::find(1);
$user->roles()->attach(1);

sync():

Similar to the attach() method, the sync() method is used to attach related models. However, the main differences are:

  • sync() accepts an array of IDs to place on the pivot table
  • Secondly, most important, the sync method will delete the data from the pivot table if the model does not exist in the array, and insert only the new items to the pivot table.

Example:

user_role

id  user_id role_id
1    12       1
2    12       5
3    12       2

$user = User::find(12);
$user->roles()->sync(array(1, 2, 3));

The above operation will delete:

id  user_id role_id
2    12       5

And insert role_id 3 to the table.

user_role table

id  user_id role_id
1    12       1
3    12       2
4    12       3

这篇关于Laravel Eloquent - 附加与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)