HasAndBelongsToMany in CakePHP
I have three Models with the associated properties:
Links Model:
var $belongsTo = array('LinkCategory');
LinkCategory Model:
var $hasMany = array('Link');
var $hasAndBelongsToMany = array('User');
User Model
var $hasAndBelongsToMany = array('LinkCategory');
With that, I would expect the following to get me all the link categories for the user.
$user_link_categories = $this->LinkCategory->find('all', array('conditions' => array('User.id' => 1)));
However, it dies with:
Unknown c开发者_开发问答olumn 'User.id' in 'where clause'
Query: SELECT LinkCategory
.id
, LinkCategory
.title
, LinkCategory
.created
, LinkCategory
.modified
FROM link_categories
AS LinkCategory
WHERE User
.id
= 1
I am new to CakePHP, but not MVC. In my mind, this should work given my associations. Have I missed something or does this just not work in CakePHP for some reason.
I have three Models with the associated properties:
Links Model:
There should be Link model, not Links. I hope that was a misprint.
LinkCategory Model:
...
var $hasAndBelongsToMany = array('User');
I guess that means that you have join table link_categories_users and therefore you need to change recursive value to 2:
$user_link_categories = $this->LinkCategory->find('all', array('recursive' => 2, 'conditions' => array('User.id' => 1)));
Or:
$user_link_categories = $this->LinkCategory->find('all', array('recursive' => 2, 'conditions' => array('LinkCategoryUser.user_id' => 1)));
Or:
$user = $this->User->find('first', array('recursive' => 2, 'conditions' => array('User.id' => 1)));
Update. This must work:
$user_link_categories = $this->LinkCategory->User->find('all', array('conditions' => array('User.id' => 1)));
LinkCategory
doesn't have a field User.id
... as a matter of fact, the way User.id
has a period in the middle suggests id
is a field which belongs to User
.
Since LinkCategory
belongsTo
a User
it probably has a field user_id
, so theoretically this should work:
$user_link_categories = $this->LinkCategory->find('all', array('conditions' => array('user_id' => 1)));
If this still doesn't work it means your DB tables don't have columns to support these relationships and you'll need to read more about associations to get to the bottom of that.
Personally, though, I think you're going backwards. You're trying to find a LinkCategory
based on their associated User
, but you can't use a field from another model (User
) like this in a simple find()
(on LinkCategory
).
Instead you should find the User with an id
of '1', then - since a User
belongsTo
a LinkCategory
- read that's User
's LinkCategory
. Again, I'm rusty, but I'm thinking it would look a little like this...
$user = $this->User->find('first', array('conditions' => array('Article.id' => 1)));
pr($user);
... make that recursive
(see here) and $user
should load your LinkCategory
as well.
精彩评论