我有这个MYSQL查询。我想选择所有以数字开头的单词。这是工作的纯MYSQL查询。
SELECT 'seriesid', 'seriesname', 'imagepath', 'views', 'scenes'
FROM `series`
WHERE `seriesname` regexp '^[0-9]+'
现在我想用Laravel实现这个。我编写了一些代码。但没有用。以下是我对上述查询的Laravel代码。
DB::table('series')->
select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->
where('seriesname', 'regexp', '''^[0-9]+''')->
get();
这段代码的错误是什么?它总是返回一个空数组[]
。
在你原来的MySQL查询中,你不寻找列数据中的引号;在你的Laravel里,你是。试着把它们去掉。
DB::table('series')->
select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->
where('seriesname', 'regexp', '^[0-9]+')->
get();
要在laravel中使用正则表达式,必须使用whereRaw()。所以修改这个代码
DB::table('series')->select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->where('seriesname', 'regexp', '''^[0-9]+''')->get();
DB::table('series')->select('seriesid', 'seriesname', 'imagepath', 'views', 'scenes')->whereRaw('seriesname regexp ?', array('''^[0-9]+'''))->get();
如果无法通过流畅接口生成所需的查询,可以随意使用whereRawhttps://laravel.com/docs/5.0/eloquent