Adding conditions to Yii model relations

Something I realised today is the power of adding conditions to model relations. This allows you to specify which records are returned as part of the relationship, which therefore allows you to set up several relationships for different situations.

for example:

'users' => array(self::MANY_MANY, 'User', 'user2project(project_id, user_id)', 'condition' => 'accepted = 1'),

This only brings back users who have accepted an invitation.

I can then also set up a new relation, called ‘invitedUsers’ where the condition is the opposite.

This allows me to access the users easily:

$project = Project::model()->findByPk(1); $users = $project->users; $invitedUsers = $project->invitedUsers;

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>