简体   繁体   English

Laravel雄辩地替换和比较

[英]Laravel eloquent where replace and compare

I've a phone number column in the users table. 我在users表中有一个phone number列。 The phone numbers are in different formats: 电话号码有不同的格式:

  • 123-456-7890 123-456-7890
  • (123) 456 7890 (123)456 7890

    etc... 等等...

I would like to compare by removing the extra characters and retrieve the results. 我想通过删除多余的字符进行比较并检索结果。

Here is the mysql query : 这是mysql查询

SELECT * FROM users WHERE REPLACE(REPLACE(REPLACE(`phonenumber`, '-', ''), '(', ''), ')', '') = '1234567890'

How can do I this in the Laravel Eloquent? 我该如何在Laravel口才中做到这一点?

I know the best option would be to force the formatting on the DB column. 我知道最好的选择是在DB列上强制设置格式。 I'm wondering if we can do this with Laravel Eloquent. 我想知道我们是否可以通过Laravel Eloquent做到这一点。

It's not going to be database-agnostic, but: 它不会与数据库无关,但是:

$query->whereRaw('REPLACE(REPLACE(REPLACE(`phonenumber`, '-', ''), '(', ''), ')', '') = ?', [$phoneNumber]);

See Raw Methods at https://laravel.com/docs/5.7/queries#raw-expressions 请参阅https://laravel.com/docs/5.7/queries#raw-expressions上的 原始方法


The better approach would be to remove these characters before inserting the numbers into the database. 更好的方法是在将数字插入数据库之前删除这些字符。

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

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