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"?

phil_g
  • 516
  • 6
  • 13

1 Answers1

0

Yii does support Many_TO_Many relations (to some degree) and this support has been improving through the 1.1.x releases http://www.yiiframework.com/doc/guide/database.arr.

Generally i don't think you will have to use CDbCommand & get dirty with SQL, you shouldn't face any problems doing it with AR specially the retrieval part, However, Insertion (Create/Update) Could be a problem (not a huge one though) since it can be solved with some triggers either on database level (database triggers) or App level (Model afterCreate() & afterUpdate()) to automate populating/updating the middle table (pivot) records.

Another (cleaner) way would be to use this extension: http://www.yiiframework.com/extension/cadvancedarbehavior/ which should do the job for you.

Last thing: take a look at this question and this one for related inquires.

Community
  • 1
  • 1
Nimir
  • 5,727
  • 1
  • 26
  • 34
  • Thank you for your answer. I saw the extension and the links before, but with no result. Yes, I don't have problems with retrieval, but I don't actually need to update the **models**. All I need is to insert or delete a row into a relation table. Honestly, I've just tried the extension, it doesn't work. `$book->save()` always fails and returns false. I had to return the CDbCommand. It's sad that I don't have much time to dig deeper (as I'm an Yii newbie I'll need plenty of time), but I hope to get beck to the problem later... – phil_g Aug 20 '12 at 00:58
  • well, i still think investing in fixing your problem with the extension (& you should add related details to the Q, if you choose so) is better than investing in making a monkey patching with `CDbCommand` but its your choice!! – Nimir Aug 21 '12 at 20:07