【问题标题】:Cakephp contain is included in queryCakephp 包含包含在查询中
【发布时间】:2014-10-18 10:53:17
【问题描述】:

当我运行以下代码时,Containable 行为不起作用。 我不想使用手动加入!

$data = $this->Variant->find('first', array(
        'contain' => array('VariantValue'),
        'conditions' => array(
            'Variant.product_id' => $product_id
        ),
        'group' => 'VariantValue.variant_id having count(*) = 2'
));

数据库:

CREATE TABLE `variants` (
   `id` int(11) NOT NULL,
   `product_id` int(11) NOT NULL,
   `price` decimal(7,2) NOT NULL
)    

CREATE TABLE `variant_values` (
   `id` int(11) NOT NULL,
   `variant_id` int(11) NOT NULL,
   `value_id` int(11) NOT NULL
)

模型:

class Variant extends AppModel {

    public $actsAs = array('Containable');
    public $belongsTo = array(
        'Product' => array(
            'className' => 'Product',
            'foreignKey' => 'product_id'
         )
    );
    public $hasMany = array('CartVariant', 'VariantValue');
}

class VariantValue extends AppModel {

    public $actsAs = array('Containable');
    public $belongsTo = array(
        'Value' => array(
            'className' => 'Value',
            'foreignKey' => 'value_id'
        ),
        'Variant' => array(
            'className' => 'Variant',
            'foreignKey' => 'variant_id'
        )
    );
}

错误信息:

错误:SQLSTATE[42S22]:未找到列:1054 组语句中的未知列 VariantValue.variant_id

SQL 查询: SELECT Variant.id, Variant.product_id, Variant.price FROM variables AS Variant WHERE Variant.product_id = 1 GROUP BY VariantValue.variant_id count(*) = 2

【问题讨论】:

标签: mysql cakephp containable


【解决方案1】:

尝试从 VariantValue 角度编写代码:

$data = $this->Variant->VariantValue->find('first', array(
        'contain' => array(
              'Variant' => array(
                  'conditions' => array('Variant.product_id' => $product_id))),
        'group' => 'VariantValue.variant_id HAVING count(*) = 2'
));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2014-05-15
    相关资源
    最近更新 更多