1
votes

I have trouble with relations in my application. I have following tables:

post:

id | title | text | label

1 | lala | lala | 1

post_label:

id | name

1 | security

2 | other

two models: Post, PostLabel

and relation in post model:

'postLabel' => array(self::HAS_ONE, 'PostLabel', 'id'),

When i use this:

$model=$this->loadModel('Post',1);

var_dump($model->postLabel);

it returns NULL, but when i use:

$model=$this->loadModel('Post',1);

var_dump($model->title);

it returns 'lala'

Where I made mistake?

Edit: I see in sql query there is using post id, but not label id. How to change this?

3
What returns NULL? Is $model null or $model->postLabel? Please post the resulting SQL query. - Kai
$model->postLabel return NULL. Query: "SELECT postLabel.id AS t1_c0, postLabel.name AS t1_c1 FROM post_label postLabel WHERE (postLabel.id='1009')`" - andrzej1_1

3 Answers

4
votes

I know it sounds counter intuitive (it took me some time to get used to), but you actually need to use BELONGS_TO relation, not HAS_ONE.

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

KEY POINT: A BELONGS_TO relation says that a field in this model points to the primary key in another model; in this case, the current model owns the linking field.

KEY POINT: A HAS_ONE relation says that some other model has a linking field pointing to this model's primary key; in this case, the related model owns the linking field.

Because label is key in this (Post) model that points to primary key of another (PostLabel) model, you need to use BELONGS_TO relation.

So your relation definition should look like this:

'postLabel' => array(self::BELONGS_TO, 'PostLabel', 'label')
1
votes

Your relation uses the wrong foreign key column. It must be label:

'postLabel' => array(self::HAS_ONE, 'PostLabel', 'label'),
0
votes

You don't have any table or attribute to make the join between the 2 tables!

Post has only id | title | text | category and post_label id | name but how do we know what label belongs to what post?!

In post_label You should have a field like post_id and in your relations you'll declare

'postLabel' => array(self::HAS_ONE, 'PostLabel', 'post_id'),

Then you'll get something!