简体   繁体   中英

How to select words start with a number in Laravel eloquent ORM?

I have this MYSQL query. I want to select all the words starting with a number. This is the working pure MYSQL query.

SELECT 'seriesid', 'seriesname', 'imagepath', 'views', 'scenes'
    FROM `series`
    WHERE `seriesname` regexp '^[0-9]+'

Now I want to implement this using Laravel. I made some codes. But not working. Here's my Laravel code for above query.

DB::table('series')->
    select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->
    where('seriesname', 'regexp', '\'^[0-9]+\'')->
    get();

What's the error in ths code ? It always returns an empty array [] .

In your original MySQL query, you aren't looking for quotes in the column data; in your Laravel one, you are. Try removing them.

DB::table('series')->
    select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->
    where('seriesname', 'regexp', '^[0-9]+')->
    get();

To use regex in laravel you have to use whereRaw(). So change this code

DB::table('series')->select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->where('seriesname', 'regexp', '\\'^[0-9]+\\'')->get();

TO

DB::table('series')->select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->whereRaw('seriesname regexp ?', array('\\'^[0-9]+\\''))->get();

If you are unable to generate the query you need via the fluent interface, feel free to use whereRaw https://laravel.com/docs/5.0/eloquent

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