Yii2-有效记录 - 条件组

Sas*_*sha 2 php yii2

我需要编写如下所示的查询:

(WHERE metrics = kg && quantity <xx)|| (WHERE metrics = lbs && quantity <(xx*2.2046))

这可能与Yii Active Record有关,如果可以的话?

top*_*her 7

根据您希望如何使用查询构建器,有许多选项.以下是一些:

1)您可以将条件作为字符串插入:

Product::find()->where("(metrics = 'kg' AND quantity < :quantity) 
                   OR (metrics = 'lbs' AND quantity < :quantity_lbs))",
                   [":quantity" => $quantity, ":quantity_lbs" => $quantity * 2.2]
              )->all(); 
Run Code Online (Sandbox Code Playgroud)

2)或者通过以下方式分割条件OR:

Product::find()->where("(metrics = 'kg' AND quantity < :quantity)") 
               ->orWhere("(metrics = 'lbs' AND quantity < :quantity_lbs)")
               ->addParams([":quantity" => $quantity, ":quantity_lbs" => $quantity * 2.2])
               ->all();
Run Code Online (Sandbox Code Playgroud)

3)或使用运营商:

Product::find()->where(['metrics' => 'kg', ['<', ['quantity' => $quantity]]]) 
               ->orWhere(['metrics'=> 'lbs', ['<', ['quantity' => $quantity * 2.2]]]) 
               ->all();
Run Code Online (Sandbox Code Playgroud)

我会选择第二个选项.它是最易读的,更易于维护.