Cakephp3查询模型

时间:2015-05-27 10:23:41

标签: cakephp cakephp-3.0

这是我的产品型号:

$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'
]);

我的查询:

$result = $this->Products->find('all', [
    'contain' => [
        'RefundProducts' => [
            'PriceUnits',
            'conditions' => $refund_condition,
        ]
    ]
]);

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

3 个答案:

答案 0 :(得分:1)

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

$result = Products->find()->contain(['RefundProducts' => function ($q) {
   return $q
        ->select(['field1', 'field2'])
        ->where(['refunded_product' => true])]);

答案 1 :(得分:1)

这是 matching() 方法的工作,它将使用RefundProducts创建INNER JOIN,因此您只能获得 Products 有一些 RefundProductscontain中的条件仅限制获取的关联

 $result = $this->Products->find()
    ->contain(['RefundProducts' => function ($q) use ($refund_condition) {
        return $q->where($refund_condition);
    }])
    ->matching('RefundProducts')
    ->distinct(['Products.id']);

我不确定$refund_condition应该做什么。此示例将Products得到RefundProducts,但只有在RefundProducts满足时才会包含$refund_condition(因此RefundProducts可以返回为空)。或者,根据您要过滤的内容,您可以这样做

->contain(['RefundProducts'])
->matching('RefundProducts', function ($q) use ($refund_condition) {
    return $q->where($refund_condition);
})

答案 2 :(得分:0)

使用where检查是否使用了相关表格(在这种情况下为RefundProducts)的列:

// in your query-object
$query->where(['Table.column IS NOT NULL']);