Reputation: 431
I have a chat
table with fields
admin TINYINT
owner_id INTEGER
The goal is to have two relations in Yii:
'admin'=>array(
self::BELONGS_TO, 'Admin', 'owner_id',
'condition'=>'admin=1',
),
'user'=>array(
self::BELONGS_TO, 'User', 'owner_id',
'condition'=>'admin=0',
),
However, I got General error: 1 no such column: admin
, and could manage only by adding all_ones
and all_zeros
columns to Admin table, so I could write
'admin'=>array(
self::BELONGS_TO, 'Admin', array('owner_id' => 'id', 'admin' => 'all_ones'),
),
'user'=>array(
self::BELONGS_TO, 'User', array('owner_id' => 'id', 'admin' => 'all_zeros'),
),
What is the way I could implement that without using such a hacks?
Upvotes: 2
Views: 4445
Reputation: 714
Solution 1:
Put your relations on User model (because the relation condition does filter the related model, not the model the relation is defined on)
//On the User model:
'chatsAdmin'=>array(
self::HAS_MANY, 'Chat', 'owner_id',
'condition'=>'admin=1',
),
'chats'=>array(
self::HAS_MANY, 'Chat', 'owner_id',
'condition'=>'admin=0',
),
Solution 2:
Use finder to get a filtered set of Chats (or DataProvider)
//relation on chat (without condition!)
'user'=>array(self::BELONGS_TO, 'User', 'owner_id')
//finder on chat model, will return ALL (use CActiveDataProvider if you need paging..)
Chat::model()->with('user')->findAll('user.admin=:admin', array(':admin'=>1))
Upvotes: 3