【问题标题】:cakephp 3 matching only if row existscakephp 3 仅在行存在时匹配
【发布时间】:2017-01-03 18:46:34
【问题描述】:

我正在使用 CakePHP 3.2。

我有三个表categoriesproductsseller_products

我想从所有表中检索数据,其中 seller_products.stock > 0seller_products.status = 1 也是 GROUP BY categories

这段代码运行良好

$pros1 = $this->Products->Categories->find()
    ->where([
    ])
    ->select(['Categories.id', 'Categories.title'])
    ->distinct(['Categories.id'])
    ->contain([
        'Products' => ['conditions' => ['status' => 1]], 'Products.SellerProducts',
    ])
    ->matching('Products.SellerProducts', function(\Cake\ORM\Query $q) {
    return $q->where(['SellerProducts.stock >' => 0, 'SellerProducts.status' => 1]);
});

他们的关联是

$categories->hasMany('Products', [
   'foreignKey' => 'category_id'
]);
$products->hasMany('SellerProducts, [
   'foreignKey' => 'product_id'
]);

现在,问题来了。

这个查询甚至返回那些在SellerProducts.product_id中没有退出的产品

如何只获取SellerProducts中存在且满足匹配条件的产品?

【问题讨论】:

    标签: cakephp cakephp-3.2


    【解决方案1】:

    您需要使用内部连接查询进行调用。请尝试以下代码:

    $pros1 = $this->Products->Categories->find()
            ->where([])
            ->select(['Categories.id', 'Categories.title'])
            ->distinct(['Categories.id'])
            ->contain([
                'Products' => ['conditions' => ['status' => 1]], 'Products.SellerProducts',
            ])
            ->innerJoinWith('Products.SellerProducts', function(\Cake\ORM\Query $q) {
                return $q->where(['SellerProducts.stock >' => 0, 'SellerProducts.status' => 1]);
            });
    

    更多详情,请访问http://book.cakephp.org/3.0/en/orm/query-builder.html#using-innerjoinwith

    【讨论】:

    • 如果您添加一些关于它究竟是如何 不起作用的详细信息,这将使人们对可能的修复方式有所了解。 “不工作”是如此含糊,以至于您不太可能得到有用的反馈。
    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多