Yii 1.1: Relations some example and links

on

In Model there is a function called relations.

The array items are like that:

[code language=”php”]

‘VarName’=>array(‘RelationType’, ‘ClassName’, ‘ForeignKey’, …additional options)

[/code]

RelationType can be:

  • BELONGS_TO
  • HAS_MANY
  • HAS_ONE
  • MANY_MANY

Example:

[code language=”php”]
<pre>array(
        ‘posts’=&gt;array(self::HAS_MANY, ‘Post’, ‘author_id’),
        ‘profile’=&gt;array(self::HAS_ONE, ‘Profile’, ‘owner_id’),
     );
$post=Post::model()-&gt;findByPk(10);
$author=$post-&gt;author;
$posts=Post::model()-&gt;with(‘author’,’categories’)-&gt;findAll();
$posts=Post::model()-&gt;with(‘author.profile’,’author.posts’,’categories’)-&gt;findAll();
$posts=Post::model()-&gt;findAll(array(
    ‘with’=&gt;array(
        ‘author.profile’,
        ‘author.posts’,
        ‘categories’,
    )
));
$users=User::model()-&gt;with(array(
    ‘posts’=&gt;array(
        ‘select’=&gt;false,
        ‘joinType’=&gt;’INNER JOIN’,
        ‘condition’=&gt;’posts.published=1’,
    ),))-&gt;findAll();

$posts=Post::model()-&gt;with(‘author’, ‘author.group’)-&gt;findAll(array(
  ‘order’=&gt;’group.name, author.name, t.title’
));</pre>
[/code]

In model relations:

[code language=”php”]

array(

‘owner’ =&gt; array(self::BELONGS_TO, ‘User’, ‘owner_id’),

‘project’ =&gt; array(self::BELONGS_TO, ‘Project’, ‘project_id’),

‘requester’ =&gt; array(self::BELONGS_TO, ‘User’, ‘requester_id’),

);

[/code]

In view widget zii.widgets.CDetailView:

[code language=”php”]

array(

‘name’=&gt;’type_id’,

‘value’=&gt;CHtml::encode($model-&gt;getTypeText())

),

array(

‘name’=&gt;’status_id’,

‘value’=&gt;CHtml::encode($model-&gt;getStatusText())

),

[/code]

Source:

http://www.yiiframework.com/doc/guide/1.1/en/database.arr

http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/

http://www.yiiframework.com/wiki/385/displaying-sorting-and-filtering-hasmany-manymany-relations-in-cgridview/

Book: Agile Web Application Development with Yii 1.1 and PHP5

Leave a Reply

Your email address will not be published. Required fields are marked *