CakePHP检索HABTM数据
快速设置:CakePHP检索HABTM数据,cakephp,has-and-belongs-to-many,Cakephp,Has And Belongs To Many,快速设置:Userhasandbelongtomany课程 courses_users __________________________ id | user_id | course_id | 1 | 1 | 1 | 2 | 1 | 3 | 3 | 2 | 5 | 我需要使用users.id=1为用户加载所有课程 我试过这个: $this->User->id = $this-&g
User
hasandbelongtomany课程
courses_users
__________________________
id | user_id | course_id |
1 | 1 | 1 |
2 | 1 | 3 |
3 | 2 | 5 |
我需要使用users.id=1为用户加载所有课程
我试过这个:
$this->User->id = $this->Auth->user('id');
$courses = $this->User->Courses->find('all');
但是上面的代码检索所有课程,而不是与用户课程相关联的课程,因为您的关系良好,您需要执行以下操作:
$course_ids = $this->CoursesUser->find('list', array('conditions'=>array('user_id'=>$this->Auth->user('id')), 'fields'=>'course_id'));
$courses = $this->Course->find('all', array('conditions'=>array('id'=>$course_ids)));
$this->User->read(null, $id);
or
$this->User->find('first', array('conditions'=>array('id'=>1)));
它还应该为用户返回课程。这取决于你的应用程序,但我会使用可包含行为来检索课程,但实际上取决于你与用户模型的关系有多少
有了可控制的行为,您应该只加载如下关系:
$this->User->find('first',
array(
'conditions'=>array('id'=>1),
'contain'=>array('Courses')));
这不起作用,因为课程没有用户id列。因为它是一个HABTM关系,中间表有两个外键。你说的“名称”字段是什么意思?是的,courses\u users,他们有一个HABTM关系。是的,我有两个外键(course\u id和user\u id),并且它们是正确关联的(因为我可以毫无问题地插入一行)。问题是我不知道如何检索它们。我已经更新了原来的帖子,以便更好地描述这个问题。这是从中间表(我在上面的问题中画的那个表)中检索到的,现在我需要这些课程。Used recursive=1;第一行就够了。但是你能举一个例子说明我如何获得可控制的行为吗?文档不够清晰。可包含行为是CakePHP中包含的核心行为。通常我只是将其包含在AppModel中,比如:public$actsAs=array('Containable',…);然后,您可以在find中使用它,尽可能简单地指定关系表。这是一个很好的实践,因为这样,如果你有很多关系,但你只需要很少的关系,你可以用它轻量级你的查询。我认为Containable behavior doc足够清楚:bit.ly/1gjCtRc