yii-manymanyactiverecord

ManyManyActiveRecord class for simple and quick saving MANY_MANY relation data in models
9 followers

The ManyManyActiveRecord YII extension class adds up functionality of saving MANY_MANY relation field value using simple arrays.

Requirements

Yii 1.1 or above

Changes

Commit cf8a3d1 @ Aug 19, 2012

Added "save model first" exception

Commit c19cac2 @ Aug 17, 2012

Fixed issue with non integer primary keys

Commit a3da45c @ Aug 17, 2012:

Fixed issue with non 'id' primary keys
Added transaction support on setRelationRecords method

Usage

To use this extension:

1) copy ManyManyActiveRecord to your components directory

2) check that your config have autoloaded

'import'=>array(
    ...
    'application.components.*',
    ...

3) extend your model (which has MANY_MANY relation), category for example

class Category extends ManyManyActiveRecord

Then just use it:

If Category has:

'posts'=>array(self::MANY_MANY, 'Post', 'tbl_post_category(category_id, post_id)')

create tbl_post_category (category_id, post_id) table and then

you can set relations by (with erasing old ones)

$model = Category::model()->findByPk(10);
$model->setRelationRecords('posts',array(1, 2, 3));

or you can add new relations (without deletions of old ones)

$model = Category::model()->findByPk(10);
$model->addRelationRecords('posts',array(1, 2, 3));

or you can remove some relations

$model = Category::model()->findByPk(10);
$model->removeRelationRecords('posts',array(1,2,3));

or if you need to save additional data in tbl_post_category (like user_id for example) you add relations with $additionalFields

$model = Category::model()->findByPk(10);
$model->addRelationRecords('posts',array(1, 2, 3), array('user_id' => Yii::app()->user->id));

Each of this method saves data to database, you don't need to save the model.

Resources

  • [Project page] https://github.com/hastenax/yii-cmanymanyactiverecord

Be the first person to leave a comment

Please to leave your comment.

Create extension