在cakephp 1.2中,我有一个包含书籍列表的表(biblio),还有一个包含标记列表的表(tematiche)。我有这个代码来获取书籍列表:

if (isset($autore_diviso))
        {
            $dim=count($autore_diviso);
            $i=0;
            while ($i<$dim)
            {
                $conditions[]=array ('autori LIKE ?' => array(
                    '%' . $autore_diviso[$i][0] . '%'));
                $i++;
            }
        }
        else
            $conditions[]=array('autori LIKE' => "%$a%");
        if (!$anno&&!$anno2)    // Da sistemare.
            $conditions=$conditions;
        else {
        if (!$anno)
            $conditions[] = array('anno <=' => "$anno2");
        if (!$anno2)
            $conditions[] = array('anno >=' => "$anno");
        }
        if ($anno&&$anno2)
            $conditions[] = array('anno BETWEEN ? AND ?' => array($anno,$anno2)); }

现在我还需要一本书的标签,如何将其添加到这个查询中?

最佳答案

尝试在控制器中绑定Tag model
控制器内

<?php

$this->Book->bindModel(array
(
    'hasMany' => array
    (
        'Tag' => array
        (
            'foreignKey' => false,
            'conditions' => array
            (
                'Book.id = Tag.book_id'
            )
        )
    )
));

$books = $this->Book->find('all',array
(
    'conditions' => array
    (
        'Book.id' => 'SOME_ID'
    )
));

pr($books);
exit;

以上调试结果
Array
(
    [Book] => Array
    (
        [id] => SOMEID
        [name] => BOOKNAME
    )
    [Tag] => Array
    (
        [0] => Array
        (
            [id] => 1
            [name] => TAGNAME
            [book_id] => SOME_ID
        )
        [1] => Array
        (
            [id] => 2
            [name] => TAGNAME
            [book_id] => SOME_ID
        )
        [2] => Array
        (
            [id] => 4
            [name] => TAGNAME
            [book_id] => SOME_ID
        )
    )
)

关于mysql - 来自2个不同表的SQL查询cakePHP 1.2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14848725/

10-16 14:55