How to add collate to laravel query

社会主义新天地 提交于 2019-12-12 11:18:28

问题


I need to run a query having collate utf8_bin like so:

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?


回答1:


Since you can configure MySQL driver to use one:

'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(...);



回答2:


You can do it this way if it solves your problem:

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


来源:https://stackoverflow.com/questions/19514247/how-to-add-collate-to-laravel-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!