我想构建基本查询,即:
$query = $this->find('all')
->contain("Assets")
->order(['Transactions.created' => "DESC"])
->limit($count);
然后如果(满足某些条件)添加
->where(['asset_id' => $asset_id])
我能做到吗?或者我应该在两个版本中重复整个查询(有和没有'where'部分)?
答案 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]);
}