7 php cakephp has-and-belongs-to-many cakephp-1.2
我正在开发CakePHP 1.2应用程序.我有一个模型"用户"通过连接表定义了与其他表的几个HABTM关系.
我现在的任务是根据存储在其中一个HABTM表中的数据查找用户信息.不幸的是,当查询执行时,我的条件被拒绝,并显示有关丢失表的错误.在检查时,似乎CakePHP不包括select语句中的任何HABTM表.
我的用户HABTM关系如下:
var $hasAndBelongsToMany = array(
'Course' => array(
'className' => 'Course',
'joinTable' => 'course_members',
'foreignKey' => 'user_id',
'associationForeignKey' => 'course_id',
'conditions' => '',
'order' => '',
'limit' => '',
'uniq' => false,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'School' => array(
'className' => 'School',
'joinTable' => 'school_members',
'foreignKey' => 'user_id',
'associationForeignKey' => 'school_id',
'conditions' => '',
'order' => '',
'limit' => '',
'uniq' => false,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Team' => array(
'className' => 'Team',
'joinTable' => 'team_members',
'foreignKey' => 'user_id',
'associationForeignKey' => 'team_id',
'conditions' => '',
'order' => '',
'limit' => '',
'uniq' => false,
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
Run Code Online (Sandbox Code Playgroud)
错误是:
SQL错误:1054:'where子句'中的未知列'School.name'
最后,它正在尝试执行的查询
SELECT
`User`.`id`, `User`.`username`, `User`.`password`, `User`.`firstName`, `User`.`lastName`, `User`.`email
`, `User`.`phone`, `User`.`streetAddress`, `User`.`city`, `User`.`province`, `User`.`country`, `User
`.`postal`, `User`.`userlevel`, `User`.`modified`, `User`.`created`, `User`.`deleted`, `User`.`deleted_date
` FROM `users` AS `User` WHERE `User`.`id` = 6 AND `School`.`name` LIKE '%Test%' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
小智 5
来自食谱:http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM
一种选择是搜索Tag模型(而不是Recipe),这也将为我们提供所有相关的食谱.
$this->Recipe->Tag->find('all', array(
'conditions' => array('Tag.name' => 'Dessert')));
Run Code Online (Sandbox Code Playgroud)
我们还可以使用连接表模型(CakePHP为我们提供)来搜索给定的ID.
$this->Recipe->bindModel(array('hasOne' => array('RecipesTag')));
$this->Recipe->find('all', array(
'fields' => array('Recipe.*'),
'conditions' => array('RecipesTag.tag_id' => 124) // id of Dessert
));
Run Code Online (Sandbox Code Playgroud)
也可以创建一个奇特的关联,以便根据需要创建尽可能多的连接以允许过滤,例如:
$this->Recipe->bindModel(array('hasOne' => array('RecipesTag',
'FilterTag' => array(
'className' => 'Tag',
'foreignKey' => false,
'conditions' => array('FilterTag.id = RecipesTag.tag_id')
))));
$this->Recipe->find('all', array(
'fields' => array('Recipe.*'),
'conditions' => array('FilterTag.name' => 'Dessert')
));
Run Code Online (Sandbox Code Playgroud)
FWIW,您的连接表确实看起来“名称奇怪”,因为它们不遵循此处描述的约定:
http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM
无论如何,祝你好运,我记得 HABTM 在 CakePHP 中是一个令人头疼的问题。
| 归档时间: |
|
| 查看次数: |
25567 次 |
| 最近记录: |