Yii框架多对多关系
Yii框架中保存和更新多对多关系的方法是什么?
What is the method to save and update Many to Many relationship in Yii framework?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Yii框架中保存和更新多对多关系的方法是什么?
What is the method to save and update Many to Many relationship in Yii framework?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
作为行为有更好的实现。
http://www.yiiframework.com/forum/index.php?/topic/6905-please-test-my-ar-enhancement-automatically-sync-many-many-table-调用时保存/
There is a better implementation as behavior.
http://www.yiiframework.com/forum/index.php?/topic/6905-please-test-my-ar-enhancement-automatically-sync-many-many-table-when-calling-save/
除非您为两个主表之间的表创建模型,否则唯一的选择是使用 DAO(数据库访问对象)并用它指定 SQL。
看看博客演示如何完成此任务。
Unless you create a model for the table between the two main tables, your only option is to use DAO (Database Access Object) and specify SQLs with it.
Have a look at how blog demo accomplishes this task.
使用
MANY_MANY
关系类型在模型之间建立多对多连接(需要关联表将多对多关系分解为一对多关系)现在您可以使用 Active Records 的所有关系函数
Yii 框架 - Yii 权威指南:使用数据库-关系活动记录
use
MANY_MANY
relationship type to setup many to many connection between Models (An associative table is needed to break a many-to-many relationship into one-to-many relationships)And now you can use all relational functions of Active Records
Yii Framework - The Definitive Guide to Yii: Working with Databases-Relational Active Record
以下扩展可以满足您的需求...
Yii 框架 - 扩展:cadvancedbehavior
需要注意的重要事项:每次更新时,扩展都会清除所有内容以前的记录并创建新的记录。因此,当中间表包含外键以外的额外数据时,我不会使用它。
The following extension does what you want...
Yii Framework - Extension: cadvancedbehavior
An important thing to note: On each update, the extension clears all previous records and creates new ones. So I wouldn't use it when the intermediatry table contains extra data other than the foreign keys.
您可以在 mysql 级别进行设置..通过转到 phpmyadmin 中每个表下的关系视图并提供必要的关系条件..并在关系内的模型类中使用 MANY_MANY ..
you could set that up in mysql level..by going to relational view under each table in phpmyadmin and provide necessary relational condition..and use MANY_MANY in the model class inside relations..
这个问题太常见了。
通常,具有多对多关系的数据组件按顺序且独立地出现。所以你只需要一个接一个地执行插入操作。
如果您的关系需要依赖更新,您应该在数据库级别使用SQL 触发器。这将确保数据的完整性,并在应用程序的业务逻辑中提供良好的分离。
一种类似的方法是将关系数据封装在 PHP 级别的一个逻辑模型中(例如,使用 2-3 个 AR 模型进行操作)并在其中模拟 SQL 触发器逻辑。
The question is too common.
Usually data components with MANY to MANY relationships appear sequentially and independently. So you just need to do one insert action after another.
If your relationship needs dependent update you should user SQL triggers on the DataBase level. That'll ensure integrity of data and give a quite good separation in business logic of the application.
A similar way is to incapsulate relational data in one logical model on PHP level (and e.g. manipulate with 2-3 AR models there) and emulate SQL triggers logic in it.