具有多个JOINS的CakePHP模型

时间:2014-11-11 12:51:35

标签: mysql cakephp models

我有一个使用表的模型,但并不真正代表表。该模型应使用此表并使用不同的模型执行多个连接,比如说其他5个模型。这是最好的方法吗?你会单独定义连接,然后将它们合并到一个连接数组中,如下所示?这是最好的方法吗?

        $PlansJoin = array(
            "table" => "plans_master",
            "alias" => "Plan",
            "type" => "INNER",
            "conditions" => array(
                "Plan.plan_id = KpiReporter.plan_id"
            )
        );

        $BrandJoin = array(
            "table" => "brands",
            "alias" => "Brand",
            "type" => "INNER",
            "conditions" => array(
                "Brand.brand_id = Plan.brand_id",
                "OR" => array(
                    "Brand.brand_id" => $options["brand"],
                    "'all'" => $options["brand"]
                )
            )
        );

        $UserJoin = array(
            "table" => "users",
            "alias" => "User",
            "type" => "INNER",
            "conditions" => array(
                "User.user_id = KpiReporter.user_id"
            )
        );



       return $this->find("all", array(
                    "fields" => array_keys($this->virtualFields),
                    "joins" => $joins,
                    "group" => $group,
                    "conditions" => $conditions,
                    "order" => $order
        ));

可以将关联用于这些复杂的查询吗?

2 个答案:

答案 0 :(得分:0)

为什么不使用bindModel()方法 http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

或使用可包含的行为.. http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

我已经使用过两者,我发现可以更容易实现。

答案 1 :(得分:0)

当你使用cakephp =>它会改变你的生活http://book.cakephp.org/2.0/fr/core-libraries/behaviors/containable.html

当您激活此“行为”时,在您的查询中,juste选择了一个数组为“包含”的联接

像这样:

return $this->find("all", array(
                    "fields" => array_keys($this->virtualFields),
                    "joins" => $joins,
                    "group" => $group,
                    "conditions" => $conditions,
                    "order" => $order,
                    "contain"=> array('NameOfLinkedModel')

        ));