简体   繁体   中英

Eloquent: Query the length of field in Laravel

I want to do something like that in Laravel (valid sqlite query):

select * from 'tbUsers' where  length(name)>50;

I tried

User::with('Permissons')->where('LENGTH(name)','>','50')->get();

But it seems not to work........

note : other queries works without problem:

User::with('Permissons')->where('active','=','1')->get();

试试这个whereRaw( string $sql, array $bindings = array(), string $boolean = 'and')

User::with('Permissons')->whereRaw('LENGTH(name) > 50')->get();

使用whereRaw

User::with('Permissons')->whereRaw('LENGTH(name) > ?', [50])->get();

In your test you tried 'LENGTH(name)' , but this converts to a string which means the select statement becomes more like:

select * from 'tbUsers' where 'LENGTH(name)' > 50;

Which is bad. In order to stop treating it as a string you need to let where() know what you're entering is raw-sql, to do that you can use DB::raw :

User::with('Permissons')->where(DB::raw('LENGTH(name)'),'>','50')->get();

Instead of using simple LENGTH(name) use char_length(name) to get length of characters in string. LENGTH() returns the length of the string measured in bytes. CHAR_LENGTH() returns the length of the string measured in characters.

For Example:

LENGTH('déjà vu')  => 9
CHAR_LENGTH('déjà vu') => 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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