mysql - Cakephp contains 包含在查询中

标签 mysql cakephp containable

当我运行以下代码时,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 变体 AS Variant WHERE Variant.product_id = 1 GROUP BY VariantValue.variant_id 具有 count(*) = 2

最佳答案

尝试从 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'
));

关于mysql - Cakephp contains 包含在查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26438981/

相关文章:

python - django manage.py migrate 命令是否创建数据库/模式(如果不存在)?

mysql - 标签系统的最佳模型

CakePHP3 将 View 渲染为变量

cakephp - 排除 CakePHP 中的 hasMany 模型

CakePHP 可容纳的订单条件不起作用

mysql - 如何在 MySQL 中的 Select 语句中连接字符串

string - 防止 CakePHP 从作为参数传递的 url 中剥离字符?

php - Cakephp 和模板

cakephp - 具有 Containable 条件的分页适用于 hasOne,但不适用于 hasMany

php - 在php中的数组内添加新的键,值(值= 1)