简体   繁体   English

如何将整理添加到 Laravel 查询

[英]How to add collate to laravel query

I need to run a query having collate utf8_bin like so:我需要运行一个像这样collate utf8_bin的查询:

SELECT * FROM `table` WHERE `field`='value' collate utf8_bin;

This is strictly for an admin script and I don't want to update the table charset itself, just for the particular query.这是严格的管理脚本,我不想更新表字符集本身,只是为了特定的查询。

Can I do this using the Eloquent ORM or do I need to write this query out?我可以使用 Eloquent ORM 来做到这一点还是我需要写出这个查询?

如果它解决了您的问题,您可以这样做:

SomeModel::whereField($value)->orderByRaw("name COLLATE utf8_bin ASC")->get();

Since you can configure MySQL driver to use one:由于您可以将 MySQL 驱动程序配置为使用一个:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

You can create a different connection for your particular query:您可以为您的特定查询创建不同的连接:

'mysql-collation' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => '<your collation>',
    'prefix'    => '',
),

And use that connection on your query:并在您的查询中使用该连接:

$users = DB::connection('mysql-collation')->select(...);

EDIT:编辑:

On a Model, you probably will be able to set a connection this way:在模型上,您可能可以通过以下方式设置连接:

$posts = new Word;
$posts->setConnection('mysql-collation');
$posts->where(...);

If you only need to apply this to the values in the WHERE clause:如果您只需要将此应用于 WHERE 子句中的值:

$value = "àBc123";
$query->whereRaw('field_name COLLATE utf8mb4_bin = (?)', $value);
  • This query is both case sensitive and accent sensitive .此查询区分大小写重音
  • Replace utf8mb4_bin with whatever collation makes sense on your system (eg. utf8_bin ).utf8mb4_bin替换为对您的系统有意义的任何排序规则(例如utf8_bin )。
  • Using (?) should utilize Laravel's query sanitization.使用(?)应该利用 Laravel 的查询清理。

For accent sensitive but NOT case sensitive:对于重音敏感区分大小写:

$value = "àBc123";
$query->whereRaw('LOWER(field_name) COLLATE utf8mb4_bin = (?)', strtolower($value));

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

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