我想获取记录表2模型(预订和消息),两个模型都没有任何关系。
我尝试了很多,但它不起作用 我使用了那段代码(http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables)
$options['joins'] = array(
array('table' => 'books_tags',
'alias' => 'BooksTag',
'type' => 'inner',
'conditions' => array(
'Book.id = BooksTag.book_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions' => array(
'BooksTag.tag_id = Tag.id'
)
)
);
$options['conditions'] = array(
'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options);
答案 0 :(得分:0)
试试这个:
BookModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'book_id'
)
);
TagModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'tag_id'
)
);
BooksController中:
$this->Book->Behaviors->load('Containable');
$this->Book->find('all', array(
'contain' => array(
'BooksTag' => array(
'Tag',
),
),
));
答案 1 :(得分:0)
我更喜欢在许多查询中执行此操作。首先找到所需的标签:
$this->loadModel('Tag');
$tag = $this->Tag->find('first', array('conditions' => array('Tag.tag' => 'Novel')));
$tag_id = $tag['Tag']['id'];
然后找book_ids
:
$this->loadModel('BookTag');
$book_ids = $this->BookTag->find('list', array('conditions' => 'BookTag.tag_id' => $tag_id, 'fields' => 'book_id, book_id'));
然后找书:
$this->Book->find('all', array('conditions' => array('Book.id' => $book_ids)));
这是一个很长的代码,但运行速度快,易于理解。另一种方法是使用子查询,但它们很丑陋,可能会降低您的应用程序的速度