我的架构具有以下关系:
User hasMany Transaction belongsTo User
Item hasMany Transaction belongsTo Item
User hasManyAndBelongsTo Item using Transaction as join table
我想返回给定项目符号属于给定用户 ID 的所有项目。我可以使用
检索属于用户的所有项目$this->User->find('all', array( 'conditions' =>
array( 'User.id' => $userId ) ) )
我可以使用
检索具有给定项目名称的所有项目$this->Item->find( 'all', array( 'conditions =>
array( 'Item.symbol' => $itemSymbol ) );
但是如果我尝试在 $this->Item->find(), $this->Item 上使用条件数组( 'Item.symbol' => $itemSymbol, 'User.id' => $userId ) ->User->find()、$this->User->find() 或 $this->User->Item->find(),我收到错误
SQL Error: 1054: Unknown column 'Item.id' in 'where clause'
或
SQL Error: 1054: Unknown column 'Item.symbol' in 'where clause'
我已经阅读了所有版本的食谱中的 HABTM,并阅读了数十篇关于它的论坛/SO 帖子,但我在形成这个查询方面没有任何运气。
相关信息: //User.php 关联
// a user hasMany transactions
var $hasMany = array('Transaction' =>
array('className' => 'Transaction',
'order' => 'Transaction.created DESC', // order by descending time of transaction
//'limit' => '1', // change this if we need more, for example, if we need a user transaction history
'foreignKey' => 'user_id',
)
);
// a user hasAndBelongsTo items through transactions
var $hasAndBelongsToMany = array('Item' =>
array('className' => 'Item',
'joinTable' => 'transactions',
'foreignKey' => 'user_id',
'associationForeignKey' => 'item_id',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
//Item.php关联
var $hasMany = array('Transaction' =>
array('className' => 'Transaction',
'order' => 'Transaction.created DESC',
//'limit' => '1', // change this if we need more, for example, if we need a item transaction history
'foreignKey' => 'item_id',
)
);
// a item hasAndBelongsTo users through transactions
var $hasAndBelongsToMany = array('User' =>
array('className' => 'User',
'joinTable' => 'transactions',
'foreignKey' => 'item_id',
'associationForeignKey' => 'user_id',
'order' => '',
'limit' => '',
'unique' => true,
'finderQuery' => '',
'deleteQuery' => '',
)
);
//Transaction.php 关联:
var $belongsTo = array('User', 'Item');
最佳答案
您正在寻找可控制的行为;例如
// app_model.php
var $actsAs = array(
'Containable'
);
我假设 User 扩展了 AppModel,因此将为子级(User)设置 Containable。现在,在您的 Controller 中,相关类的条件可以放置在 find() 的第二个 argv 的“contain”键中;例如
// users_controller.php
$this->User->find('first', array(
'conditions' => array('User.id' => $userId),
'contain' => array(
'Item' => array(
'conditions' => array('Item.symbol' => $itemSymbol)
)
)
);
Cake 会找到匹配的 User 并检索匹配的 Items(具有相同的 user_id 和指定的 Item.Symbol。但是在不需要时要非常小心地使用 'contain' => array(),否则 Cake 将检索所有已定义的关联,这会给您的数据库带来负担。
关于CakePHP 中使用 HABTM 的 find() 多模型条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4083494/