0

I was wondering if it is a good (acceptable) practice to combine those to ways of retrieving/updating database data?

For example, in my database I have two tables (Books and Users) and one "many-to-many" table Books_Users. When a user rates a book, the Books_Users table should be updated (a new record with a book_id and a user_id should be whether inserted or deleted).

I googled ways of doing it using AR methods only, but I haven't found any good solution. I ended up using CDbCommand execute() and very simple SQL-query like INSERT INTO books_users(book_id, user_id) VALUES(:bid , :uid); in a BookController action.

The point is that all my models extend CActiveRecord, and I use AR methods all the way.

So here is the question: is that kind of blending of different approaches could be used without remorse, or I should get rid of it immediately and write the code in some "proper way"?

4

1 回答 1

0

Yii 确实支持Many_TO_Many关系(在某种程度上),并且这种支持已经通过 1.1.x 版本得到改进http://www.yiiframework.com/doc/guide/database.arr

一般来说,我认为您不必使用CDbCommand和弄脏 SQL,您不应该在使用AR时遇到任何问题,特别是检索部分,但是,插入(创建/更新)可能是一个问题(不是一个大问题虽然)因为它可以通过数据库级​​别(数据库触发器)或应用程序级别(模型afterCreate()afterUpdate())的一些触发器来解决,以自动填充/更新中间表(数据透视)记录。

另一种(更清洁)的方法是使用这个扩展:http ://www.yiiframework.com/extension/cadvancedarbehavior/它应该为你完成这项工作。

最后一件事:看看这个问题和这个问题的相关查询。

于 2012-08-19T21:40:43.943 回答