【问题标题】:SQL Query cakePHP 1.2 from 2 different tablesSQL 从 2 个不同的表中查询 cakePHP 1.2
【发布时间】:2013-02-13 16:54:21
【问题描述】:

在 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)); }


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

【问题讨论】:

  • 两个表是否相关?
  • 在标签表中有书的ID
  • 你在模型中定义了关系吗?
  • 如果你在模型中定义关联很容易得到你想要的记录。

标签: mysql cakephp cakephp-1.2


【解决方案1】:

尝试在控制器中绑定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
        )
    )
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2013-09-27
    • 2021-06-06
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多