开发者

CakePHP Model Chain Find

I have an object $this->user which is of model User. This object is populated by $this->Auth->user in my app controller like so:

$this->user = ClassRegistry::init('User');
$this->user->set($this->Auth->user);

Works like a charm. If I print_r out $this->user in my controller it gives me:

User Object ( [validate] => Array ( blah blah blah

A typical object. Now I have a Group model which belongs to a User, and users have many groups. These variables are properly set in the models. Now I want to find all Groups for this particular user who is logged in. So I tried this:

$groups = $this->user->Group->find('list', array('fields'=>array('id', 'group_name')))

The key is that I want to use $this->user to automatically filter the Group query based on the owner_id in $this->user. It makes sense to me that if I've got a specific object representing a user and I do a Group query based on that user ... it should only return the relevant groups.

The problem is that $groups contains all of the entries in the Groups table, rather than obviously the ones I only want from the current user. I don't see why I would need to add a "conditions"=>"user_id"=$this->Auth->user('id') parameter to the find function because I've already specified what user I'm using via the model chain.

Any ideas why this is not working? The sql statment it ru开发者_如何学Gons is simply a SELECT on Groups WHERE 1 = 1 (so not filtering at all).


No, the object User really acts more like a class than a object. You can say Cake doesn't fully implement Active Record pattern (I think Cake 3.0 may fix that, not sure). So yes, you still need to set the condition for the find. And you don't have to set($this->Auth->user);

You are probably not very familiar with Cake: in Cake, you hardly ever have to instantiate Model objects at all. They are created for you based on the current controller and model relationships that you specify.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜