代码之家  ›  专栏  ›  技术社区  ›  Daniel Magliola

CakePHP中连接的操作顺序

  •  4
  • Daniel Magliola  · 技术社区  · 14 年前

    CakePHP有以下问题:

    在我的模型中,存款属于账户,账户属于客户。

    在查询存款时,默认情况下,我得到的是账户信息,而不是客户的信息。

    所以,我这样做了:

    'joins' => array(
        array('table'=>'customers', 'alias'=>'Customer', 'type'=>'left', 'foreignKey' => false, 'conditions'=>array('Account.customer_id = Customer.id'))
    )
    

    哪一个 几乎 作品。。。

    我从中得到的本质是:

    SELECT (...) FROM Deposits LEFT JOIN Customers LEFT JOIN Accounts
    

    SELECT (...) FROM Deposits LEFT JOIN Accounts LEFT JOIN Customers
    

    有没有规定“我的自定义联接”应该放在“常规模型联接”之后?
    或者我必须手动解除存款与帐户的绑定,并手动指定这两个联接吗?


    丹尼尔

    4 回复  |  直到 14 年前
        1
  •  2
  •   Community VonC    7 年前

    您需要取消绑定要位于顶部的模型,并在“joins”数组中包含适当的数组。看到了吗 this

        2
  •  2
  •   Sadikhasan    10 年前

    您可以使用Containable行为来选择所需内容,因此从您的控制器:

    $this->Deposit->find('all', array(
        // conditions
        'contain' => array('Account' => array('Customer'))
    ));
    

    一定要加上 actsAs 类的变量。这里有更多的信息。 http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

        3
  •  0
  •   Andy Hobbs    12 年前

    我意识到这是一个老问题,但它仍然是相关的。。。

    在添加新连接以满足关联之前,Cake会检查现有的连接。在dbo里挖了一番之后_源代码.php(cake 1.3也适用于2.x)我知道,通过指定cake构建它们的确切方式,可以有效地覆盖连接的顺序。

    所以,在你的例子中:

    'joins' => array(
    array(
        'table' => '`accounts`', 
        'alias' => 'Account', 
        'type' => 'Left', 
        'conditions' => '`Deposit`.`account_id` = `Account`.`id`'
    ),
    array(
        'table' => '`customers`', 
        'alias' => 'Customer', 
        'type' => 'Left', 
        'conditions' => '`Account`.`customer_id` = `Customer`.`id`'
    )
    )
    

        4
  •  0
  •   Community VonC    7 年前

    我也遇到过这种情况,那时我几乎被困住了。在做了一些搜索之后,我发现有两种方法可以做到这一点。

    1. 编辑核心数据库资源.php文件以更改连接顺序。( How to change the sequence of 'joins' in CakePHP? )

    我希望现在有可能的选择。如果你有任何其他有趣的方式请张贴在这里!