如何将构建查询拆分为多行?

时间:2018-04-14 11:42:24

标签: cakephp orm cakephp-3.0

我想构建基本查询,即:

            $query = $this->find('all')
            ->contain("Assets")
            ->order(['Transactions.created' => "DESC"])
            ->limit($count);

然后如果(满足某些条件)添加

            ->where(['asset_id' => $asset_id])
我能做到吗?或者我应该在两个版本中重复整个查询(有和没有'where'部分)?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$query = $this->find('all')
    ->contain([
        'Assets' => function ($assets) use ($asset_id) {
            if (isset($asset_id)) {
                $assets->where([
                    'Assets.asset_id' => $asset_id
                ]);
            }

            return $assets;
        }
    ])->order(['Transactions.created' => "DESC"])
    ->limit($count);

答案 1 :(得分:1)

简短回答:

if(isset($asset_id)){
   $query->where(['asset_id' => $asset_id]);
}