Relation help

Here’s what I have:


Table user

----------

id

name

etc...




Table feature

-------------

id

name




Table user_feature

------------------

id

user_id

feature_id

active

A User can have Many Features - I have the following relation in my User model:


'user_features'=>array(self::HAS_MANY, 'UserFeature', 'user_id', 'condition'=>'active=1'),

What I want to do is create a function ( hasFeature($id) ) whereby I can pass in the ID (or name) of a Feature and see if the user has got that feature. Ideally I want to use the above relation to do this check (get the list of features and check their IDs). So in my view file, I want to do something like this:


<?php

if($user->hasFeature(2))

{

// do some cool stuff

}

?>

This is probably straightforward but I seem to be struggling with it at the moment.

mmm…

Is the relation correct? Shouldn’t be:

‘features’=>array(self::MANY_MANY, ’Feature’,’user_feature(user_id, featured_id)’)

update:

forgot to put the condition but you know what i meant above

I don’t understand. The relation is correct (it’s in my user model and it find all the features for the current user).

in User model




public function hasFeature($id_feature){

   $res = (bool) UserFeature::model()->countByAttributes(array('user_id'=>$this->id,'feature_id'=>$id_feature));

   return $res;

}



Nevermind then, but I thought that by having two models User and Feature and both connected through a middle table then that was MANY_MANY as many users could have many features and the other way around.

If I have a relation properly set then this is what you could also do (no need for extra DB calls):




public function hasFeature($id){

  for($this->user_features as $feature)

     if($id == $feature->id) return true;

  return false;

}



Hi Antonio,

I agree with you on the MANY_MANY relation between user and features. However I’m not sure to understand why you say that in your code there is “no need for extra DB call” . For me, lazy loading would imply extra DB call when relation user_features is references (in the for loop).

Please tell me if I’m missing something here ;)

thanks

Well, yes if you are using lazy loading but that depends on the way you create the object. Remember that we can also use eager loading approach:

User::model()->with(’user_features’)…

that’s right … thanks for your reply ;)

8)