改编自查克的回答,不确定为什么编辑被推迟。
在 app/Model/Book.php 中
class Book extends AppModel {
/************************************************************************
* If you want your multiple assoc. to work you must set unique to *
* false, otherwise when you save an entry it will enforce unique *
* on book ID and subsequently your associations will delete previously *
* saved associations, acting more like "User HasMany Books". *
************************************************************************/
var $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'unique' => false
));
public function addUser($bid, $uid) {
$this->data['User']['id'] = $uid;
$this->data['Book']['id'] = $bid;
$this->save($this->data);
}
}
在 app/Controller/BooksController.php(或 UsersController)中
$this->Book->addUser($bid, $uid);
胖模型/瘦控制器。允许重复条目(您需要限制限制并检查重复项,否则默认行为会使 HMBTM 变得困难)。完全符合您的要求,您只需要提供书籍和用户 ID。
CakePHP 不倾向于鼓励复杂的关联,这是因为 HMBTM 只是一种方便,在将其与其他关联混合时应小心,根据下面提供的链接,自定义关联比 CakePHP 中的 HMBTM 更可预测
http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated