PHP Yii2 ActiveRecord使用嵌套where条件

时间:2015-08-31 08:57:22

标签: php activerecord yii2

我想使用model :: find() - >创建一个activeQuery,其中...... 应该生成如下一个sql(永远不要理解逻辑)。 没有加入,只是很多单表的条件。我想这应该很简单,我只是在某个地方失踪 我无法弄清楚如何创建这样的嵌套where条件。任何提示?

select * from article where 
( 
  (site="domain.com" AND service="electronics" AND source="reader" AND tag like "%" AND marker like "%" ) 
  OR 
  (site="domain.net" AND service="electronics" AND source like "%" AND tag like "%" AND marker like "%" )
) 
AND NOT 
( 
  (site="domain.com" AND service="electronics" AND source like "%" AND tag like "%" AND marker like "%" ) 
  OR
  (site="domain.us" AND service="electronics" AND source like "%" AND tag like "%" AND marker like "%" ) 
)

3 个答案:

答案 0 :(得分:1)

好的,我找到了答案。我使用了Model :: find() - > where()并构建了嵌套数组。这样我就可以使用ActiveRecord和所有gridview / dataprovider功能。

答案 1 :(得分:1)

您可以尝试使用'and'和'or'运算符嵌套它:

ą

将生成
    ['and', 'type=1', ['or', 'id=1', 'id=2'] ]

更多信息: https://www.yiiframework.com/doc/api/2.0/yii-db-queryinterface#where()-detail

答案 2 :(得分:0)

最简单的方法是使用DELIMITER ;; CREATE TRIGGER check_trigger BEFORE UPDATE ON your_table FOR EACH ROW IF (NEW.userbalance <= OLD.userbalance+20) THEN SET NEW.userbalance = NEW.userbalance; ELSE SET NEW.userbalance = OLD.userbalance; END IF;; DELIMITER ;

这样

findBySql

否则,如果您想要Active Data Provider,您可以这样做

$myQuery = 'select * from article where 
( 
  (site="domain.com" AND service="electronics" AND source="reader" AND tag  like "%" AND marker like "%" ) 
  OR 
  (site="domain.net" AND service="electronics" AND source like "%" AND tag  like "%" AND marker like "%" )
) 
AND NOT 
( 
  (site="domain.com" AND service="electronics" AND source like "%" AND tag like "%" AND marker like "%" ) 
  OR
  (site="domain.us" AND service="electronics" AND source like "%" AND tag like "%" AND marker like "%" ) 
)';

$model = Article::findBySql($myQuery)->all();