首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cakephp3查询模型

Cakephp3查询模型
EN

Stack Overflow用户
提问于 2015-05-27 10:23:40
回答 3查看 224关注 0票数 0

这是我的产品模型:

代码语言:javascript
复制
$this->table('products');
$this->belongsTo('OrderProducts', [
    'foreignKey' => 'order_product_id',
    'propertyName' => 'order_product',
    'joinType' => 'INNER'
]);
$this->hasMany('RefundProducts', [
    'foreignKey' => 'product_id',
    'sort' => ['RefundProducts.created' => 'DESC'],
    'propertyName' => 'refund_products',
    'className' => 'RefundProducts'
]);

我的问题是:

代码语言:javascript
复制
$result = $this->Products->find('all', [
    'contain' => [
        'RefundProducts' => [
            'PriceUnits',
            'conditions' => $refund_condition,
        ]
    ]
]);

但是它得到了所有的产品,我只想得到有RefundProducts的产品

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-05-28 06:25:31

这是matching()方法的任务,它将创建与RefundProducts的内部连接,因此您将只得到一些RefundProductsProductscontain限制中的条件仅获取关联

代码语言:javascript
复制
 $result = $this->Products->find()
    ->contain(['RefundProducts' => function ($q) use ($refund_condition) {
        return $q->where($refund_condition);
    }])
    ->matching('RefundProducts')
    ->distinct(['Products.id']);

我不知道$refund_condition该怎么做。这个示例将获得具有某些RefundProductsRefundProducts,但只有当$refund_condition满足时才会包含RefundProducts (因此RefundProducts可以返回为空)。或者,根据您想要过滤的内容,可以这样做。

代码语言:javascript
复制
->contain(['RefundProducts'])
->matching('RefundProducts', function ($q) use ($refund_condition) {
    return $q->where($refund_condition);
})
票数 1
EN

Stack Overflow用户

发布于 2015-05-27 11:11:59

Cao ThếCường,您是否尝试过这样的关系查询:

代码语言:javascript
复制
$result = Products->find()->contain(['RefundProducts' => function ($q) {
   return $q
        ->select(['field1', 'field2'])
        ->where(['refunded_product' => true])]);
票数 1
EN

Stack Overflow用户

发布于 2015-05-27 11:12:34

使用where检查是否使用了相关表的列(在本例中为RefundProducts):

代码语言:javascript
复制
// in your query-object
$query->where(['Table.column IS NOT NULL']);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30479723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档