CakePHP:检索用户的 hasAndBelongsToMany 数据
我想返回 hasAndBelongsToMany 关系中仅属于 1 个用户的数据。我不确定这里的条件: 我收到警告:
警告(512):SQL 错误:1054:“where 子句”中的未知列“UsersFood.user_id”
有人可以澄清一下吗?
return $this->find('all', array('conditions' => array(
'Food.id' => 'Usersfood.food_id',
'Usersfood.user_id' => $userid,
'User.id' => $userid
)
)
);
I want to return data which belongs to only 1 user in a hasAndBelongsToMany relationship. I'm not sure about the conditions here:
I'm getting warning:
Warning (512): SQL Error: 1054: Unknown column 'UsersFood.user_id' in 'where clause'
Can someone clarify with this?
return $this->find('all', array('conditions' => array(
'Food.id' => 'Usersfood.food_id',
'Usersfood.user_id' => $userid,
'User.id' => $userid
)
)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您设置了
$hasAndBelongsToMany
,则无需指定'Food.id' => 'Usersfood.food_id',
和'Usersfood.user_id' => $用户ID,
`
If you have
$hasAndBelongsToMany
set, you won't need to specify'Food.id' => 'Usersfood.food_id',
and'Usersfood.user_id' => $userid,
`
不应该是 FoodsUser 而不是 UsersFood 吗?
假设您遵循约定,这来自书中:“这个新连接表的名称需要包含所涉及的两个模型的名称,按字母顺序排列,并用下划线 (_) 分隔。”
现在下划线代表数据库表名。按照约定,模型名称将为 FoodsUser
Shouldn't it be FoodsUser rather than UsersFood?
Assuming you're following convention, this is from the book: "This new join table's name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ )."
Now the underscore is for the database table name. Following the convention, the model name will be FoodsUser
解决办法已经找到了。我仔细阅读了 Containable 和 Join,并决定选择 Join。
The solution has been found. I literally read through Containable and Join and decided to go with Join.
确保您已按照此页面正确定义了关系 http://book.cakephp.org /view/83/hasAndBelongsToMany-HABTM
然后查看http://book.cakephp。 org/view/474/Containable
特定用户与该用户的食物。
$this->find('first', array('conditions' => array('User.id' => 123), 'contain' => array('Food')));
或每个用户都包含食物
$this->find('all', array('contain' => array('Food')));
make sure you have defined the relation properly as per this page http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM
Then look at http://book.cakephp.org/view/474/Containable
specific user with that users food.
$this->find('first', array('conditions' => array('User.id' => 123), 'contain' => array('Food')));
or all with food per user
$this->find('all', array('contain' => array('Food')));