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.
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;
}
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).