简体   繁体   English

如何解决 Active Record Yii2 中列名的问题?

[英]How to solve problem with column name in Active Record Yii2?

I have a black list of email domains in db (table black_list_domains with fields id and domain ) and I need to validate user's email address while registration.我在 db 中有一个电子邮件域black_list_domains (表black_list_domains与字段iddomain ),我需要在注册时验证用户的电子邮件地址。

The validation must add error if user's email matches pattern '%@%domain' .如果用户的电子邮件与模式'%@%domain'匹配,则验证必须添加错误。

So, working mysql-query is:因此,工作 mysql-query 是:

SELECT * FROM `black_list_domains` WHERE '$email' LIKE CONCAT('%@%', domain)"

But when I try to make this checking in my Validator's class with Active Record:但是当我尝试使用 Active Record 在我的验证器类中进行此检查时:

BlackListDomains::find()->where(['like', $email, new \yii\db\Expression("CONCAT('%@%', domain)")])->exists();

it returns a MySQL error Column not found: 1054 Unknown column 'test@test.test' in 'where clause' ( test@test.test is user's email address).它返回一个 MySQL 错误Column not found: 1054 Unknown column 'test@test.test' in 'where clause'test@test.test是用户的电子邮件地址)。

I can make a correct query with createCommand :我可以使用createCommand进行正确的查询:

\Yii::$app->db->createCommand("SELECT * FROM `black_list_domains` WHERE '$email' LIKE CONCAT('%@%', domain)")->queryAll();

But I think it is possible to make this with Active Record.但我认为使用 Active Record 可以做到这一点。 Or not?或不?

Second argument in like comparison array is intended to be column name by default. like比较数组中的第二个参数默认为列名。 You should probably use expression for the whole condition, to avoid unnecessary escaping of % ;您可能应该对整个条件使用表达式,以避免不必要的%转义;

BlackListDomains::find()
    ->where(new \yii\db\Expression(":email LIKE CONCAT('%@%', domain)", [
        'email' => $email,
    ]))
    ->exists();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM