• Stars
    star
    100
  • Rank 340,703 (Top 7 %)
  • Language
    PHP
  • Created about 13 years ago
  • Updated over 11 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Allows to manage related records

WithRelatedBehavior

Build Status

The most powerful and smart expansion for validate/saving/linking/unlinking.

This behavior allows you to validate, insert, update and save a model along with models from its relations. It supports all relation types. All DB queries are wrapped into transactions automatically but there's a support for manual transaction handling. Composite keys are supported as well.

Installation and configuration

Copy behavior to extensions/wr directory located inside your application and add it to the model of your choice the following way:

<?php
...
public function behaviors()
{
	return array(
		'withRelated'=>array(
			'class'=>'ext.wr.WithRelatedBehavior',
		),
	);
}
...

Models that will be used in this doc examples

In the models below real DB fields are marked with @property.

Post

<?php
class Post extends CActiveRecord
{
	/**
	 * @property integer id
	 * @property integer author_id
	 * @property string title
	 * @property string content
	 */

	...
	public function relations()
	{
		return array(
			'author'=>array(self::BELONGS_TO,'User','author_id'),
			'comments'=>array(self::HAS_MANY,'Comment','article_id'),
			'tags'=>array(self::MANY_MANY,'Tag','post_tag(post_id,tag_id)'),
		);
	}
	...
}

Comment

<?php
class Comment extends CActiveRecord
{
	/**
	 * @property integer id
	 * @property integer post_id
	 * @property string content
	 */
	...
}

Tag

<?php
class Tag extends CActiveRecord
{
	/**
	 * @property integer id
	 * @property string name
	 */
	...
}

User

<?php
class User extends CActiveRecord
{
	/**
	 * @property integer id
	 * @property string username
	 * @property string password
	 * @property string email
	 */
	...
	public function relations()
	{
		return array(
			'profile'=>array(self::HAS_ONE,'Profile','user_id'),
		);
	}
	...
}

Profile

<?php
class Profile extends CActiveRecord
{
	/**
	 * @property integer user_id
	 * @property string firstname
	 * @property string lastname
	 */
	...
}

Format of the $data parameter for all methods where it's used

This parameter accepts an associative array where values are attribute or relation names.

<?php
$post->withRelated->save(true,array(
	'id','title',     // model attributes
	'comments','tags' // model relations
));

The name of the relation can be specified as a key. In this case its value is another $data array with the same rules. So you there's no limit in how many times you can nest these.

<?php
$post->withRelated->save(true,array(
	'comments'=>array(
		'id','content', // comments relation attributes
		'author',       // author relation inside comments relation models
	),
));

Note: If you'll not specify any attributes, all attributes will be saved. For relations it's the opposite: you should specify relations explicitly in order for these to be saved.

Usage

Relation types

HAS_ONE

<?php
$user=new User;
$user->username='creocoder';
$user->email='[email protected]';

$user->profile=new Profile;
$user->profile->firstname='Alexander';
$user->profile->lastname='Kochetov';

$user->withRelated->save(true,array('profile'));

HAS_MANY

<?php
$post=new Post;
$post->title='Relational saving is not a dream anymore.';
$post->content='Since WithRelatedBehavior released...';

$comment1=new Comment;
$comment1->content='Was it hard?';
$comment2=new Comment;
$comment2->content='Yes, but we made it.';

$post->comments=array($comment1,$comment2);

$post->withRelated->save(true,array('comments'));

MANY_MANY

<?php
$post=new Post;
$post->title='Relational saving is not a dream anymore.';
$post->content='Since WithRelatedBehavior released...';

$tag1=new Tag;
$tag1->name='relation';
$tag2=new Tag;
$tag2->name='save';

$post->tags=array($tag1,$tag2);

$post->withRelated->save(true,array('tags'));

BELONGS_TO

<?php
$post=new Post;
$post->title='Relational saving is not a dream anymore.';
$post->content='Since WithRelatedBehavior released...';

$post->author=new User;
$post->author->username='creocoder';
$post->author->email='[email protected]';

$post->withRelated->save(true,array('author'));

Note: As you can see, API stays the same no matter which relation type is used. Also it worth mentioning that a transaction is started before saving if DB supports it. If transaction was already started manually, behavior detects it and doesn't start its own transaction. By default, same as CActiveRecord::save() does, WithRelatedBehavior::save() validates data and starts saving it only if all models it's going to save are valid. You can disable validation by passing false to $runValidation parameter.

Recursive composite validation

As opposed to standard CModel::validate() method, WithRelatedBehavior::validate() does composite model validation. That means it validates all related models as well. Validation result is returned as a boolean value. If any of the models is not valid than result will be false. If all models are valid than result will be true. Additionally you can limit validation to model attributes as follows:

<?php
$post=new Post;
$post->title='Relational validation is not a dream anymore.';
$post->content='Since WithRelatedBehavior released...';

$comment1=new Comment;
$comment1->content='Was it hard?';
$comment2=new Comment;
$comment2->content='Yes, but we made it.';

$post->comments=array($comment1,$comment2);

$result=$post->withRelated->validate(array(
	'title',		// only `title` attribute of the Post model will be validated
	'comments'=>array(
		'content',	// only `content` attribute of the Comment model will be validated
	),
));

Linking and unlinking

TBD.

Advanced usage

An advanced usage example

<?php
$post=new Post;
$post->title='Post title';
$post->content='Post content';

$user=new User;
$user->username='someuser';
$user->email='[email protected]';

$user->profile=new Profile;
$user->profile->firstname='Vasya';
$user->profile->lastname='Pupkin';

$post->author=$user;

$comment1=new Comment;
$comment1->author=$user;
$comment1->content='Some content 1';
$comment2=new Comment;
$comment2->author=$user;
$comment2->content='Some content 2';

$post->comments=array($comment1,$comment2);

$tag1=new Tag;
$tag1->name='tag1';
$tag2=new Tag;
$tag2->name='tag2';

$post->tags=array($tag1,$tag2);

$post->withRelated->save(true,array(
	'author'=>array(
		'profile',
	),
	'comments'=>array(
		'author',
	),
	'tags',
));

In order to save post and related models an extension builds saving plan first. In the example above that before saving we need to save user model and its related profile. After doing it we'll be able to save post. Then goes comments (author is the same user). Last tags is saved. Actions mentioned are executed inside a transaction. Extension takes care about all these.

Compare with other solutions

TBD.

More Repositories

1

imperavi-redactor-widget

Imperavi Redactor WYSIWYG widget (OEM-licensed for Yii)
JavaScript
406
star
2

nested-set-behavior

AR models behavior that allows to work with nested sets tree.
PHP
157
star
3

activerecord-relation-behavior

Inspired by and put together the awesomeness of many yii extensions that aim to improve saving of related records. Comes with 100% test coverage and well structured and clean code so it can savely be used in enterprise production enviroment.
PHP
92
star
4

shopping-cart-component

Allows to put models into shopping cart and do various operations with it.
PHP
80
star
5

twig-renderer

Allows to use Twig template engine in Yii framework views
PHP
70
star
6

smarty-renderer

This extension allows you to use Smarty 3 templates in Yii.
PHP
50
star
7

taggable-behavior

Provides many useful methods and named scopes to work with model tags.
PHP
37
star
8

github-api

implementation of github api v3
PHP
36
star
9

migrate-command

This is an enhanced version of the Yii Database Migration Tool that adds module support and many more usefull features.
PHP
35
star
10

comment-module

Module that adds comments to your application. You can add comments on any AR Model you like.
PHP
29
star
11

yii

This is a read-only mirror of the yiiframework svn repository. It is updated by a jenkins-ci job every 20 minutes. IMPORTANT NOTE: Yii is on github now: https://github.com/yiisoft/yii fork their repo instead of this, will keep this thing up for a while but not sure how long...
PHP
29
star
12

eav-behavior

Implements entity-attribute-value pattern.
PHP
24
star
13

yii2-yii-bridge

Yii bridge between v1.1.x and v2.0
PHP
23
star
14

file-upload-action

Action for file uploads handling.
PHP
21
star
15

trash-bin-behavior

AR models behavior that allows to mark models as deleted and then restore them.
PHP
19
star
16

yiiext.github.com

github pages for yiiext
CSS
17
star
17

webshell-module

A web shell that allows to run yiic commands and create your own commands.
JavaScript
16
star
18

ratchetio-component

This component is the way to integrate ratchet.io service with your Yii app.
PHP
15
star
19

core

the development yii application for all yiiext extensions
PHP
13
star
20

image-component

Image processing with Imagine.
PHP
13
star
21

fancybox-widget

Wrapper around fancybox.
JavaScript
12
star
22

uploadify-widget

Allows to use jQuery uploadify plugin as a widget.
JavaScript
11
star
23

status-behavior

Provides methods and named scopes to work with model statuses.
PHP
11
star
24

chart

A set of charting widgets
PHP
11
star
25

slug-behavior

PHP
10
star
26

transliterator-component

PHP
9
star
27

pdf

Extension for PDF management
PHP
8
star
28

mobile-detect-component

Mobile devices detecting with Mobile_Detect.
PHP
6
star
29

ckeditor-widget

This extension allows to add CKEditor in a view.
PHP
5
star
30

form-component

Automated form generator.
PHP
5
star
31

zend-autoloader-component

Fast autoloader for Zend Framework classes.
PHP
5
star
32

markitup-widget

Allows to use markItUp as a widget.
JavaScript
5
star
33

filesystem-component

PHP
5
star
34

lipsum-widget

Lorem Ipsum placeholder text generator
PHP
4
star
35

zii-image-column

allows to render images inside zii CGridView.
PHP
4
star
36

commentable-behavior

PHP
3
star
37

simplemodal-widget

Wrapper around SimpleModal jQuery plugin.
JavaScript
3
star
38

set-return-url-filter

Extends default Yii returnUrl functionality.
PHP
3
star
39

blueprint-widget

A way to inject blueprint CSS framework into the page.
PHP
3
star
40

active-data-provider

PHP
3
star
41

get-url-behavior

Helps getting resource URLs.
PHP
3
star
42

phpdoc-component

Allows reading phpDoc.
PHP
3
star
43

swf-object-widget

embedding Adobe Flash Player content using SWFObject 2
JavaScript
3
star
44

shorturl-component

This extensions allows you to short url by the http://goo.gl service.
PHP
2
star
45

iconized-menu-widget

Menu with favicons for each item.
PHP
2
star
46

breadcrumbs-component

displays a list of links indicating the position of the current page in the whole website.
PHP
2
star
47

ensure-null-behavior

Forces NULL to be used instead of empty varchar.
PHP
2
star
48

extension-template

YiiExt extension template
2
star
49

forgery-session-filter

Automatically loads session specified via PHP_SESSION_ID.
PHP
2
star
50

active-form-validation-filter

Automated validation filter for CActiveForm.
PHP
2
star
51

menu-widget

PHP
1
star
52

yii-more-pager

PHP
1
star
53

dwoo-renderer

This extension allows you to use Dwoo templates in Yii.
PHP
1
star
54

cycle-widget

wraps jquery.cycle.js
JavaScript
1
star
55

quicky-renderer

This extension allows you to use Quicky templates in Yii.
PHP
1
star
56

last-value-behavior

PHP
1
star
57

chm-component

generate .chm files from html
PHP
1
star
58

adjacency-list-behavior

Adjacency list behavior
1
star
59

image-validator-component

Validatior for images, validates width, height, mime type, file size, extension
PHP
1
star
60

elfinder-widget

Helps integrating http://elrte.org/elfinder filemanager with WYSIWYG
PHP
1
star
61

multilang

Yii Components to create multi-language applications
1
star
62

tinybutstrong-renderer

Allows using tinybutstrong template engine in Yii-based projects
1
star
63

reversed-pagination

Provides the ability to create 9 to 1 navigation as bash.org.ru
PHP
1
star