Laravel 4, eloquent - 语句和操作符之间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20230828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4, eloquent - between statement and operators
提问by Shaft Hymanson
There is a query I use to run in mysql :
我用来在 mysql 中运行一个查询:
select * from my_table where $val between col1 and coL2;
It works fine, but with laravel 4, the only way to make that query is to have something like
它工作正常,但是对于 Laravel 4,进行该查询的唯一方法是使用类似
my_model::where('col1','>=',$val)->where('col2','<=',$val)
This way doesn't seem to work, because I don't have the same result when using the usual "select * ..."
这种方式似乎不起作用,因为在使用通常的“select * ...”时我没有相同的结果
Any idea ?
任何的想法 ?
Just to clarify my request : In my case i dont have "...where column between value1 and value2" but "where value between commun" So it seems to me that i can't use "wherebetween"
只是为了澄清我的要求:在我的情况下,我没有“...... value1 和 value2 之间的列”而是“公共之间的值”所以在我看来我不能使用“wherebetween”
回答by The Alpha
You may try something like this
你可以试试这样的
// Get records whose id between 3 and 6
$users = User::whereBetween('id', array(3, 6))->get();
Or using variable
或者使用变量
$id = 'id';
$from = 1;
$to = 5;
$users = User::whereBetween($id, array($from, $to))->get();
This will get all the records whose ID
between 1
and 5
.
这将获得ID
在1
和之间的所有记录5
。
回答by user1669496
This should do it...
这个应该可以...
$results = my_model::select('*')->whereRaw("$val between col1 and coL2")->get();
$results = my_model::select('*')->whereRaw("$val between col1 and coL2")->get();
I think this is pretty safe, but you may need to clean $val
first.
我认为这很安全,但您可能需要先清洁$val
。
回答by Somnath Muluk
Without creating MySQL Model, we can generate query like:
在不创建 MySQL 模型的情况下,我们可以生成如下查询:
// If column value need to checked between value 1 and value 2
$DBConnection->table('users')->whereBetween('id', array(3, 6))->get();
// If value need to checked between column 1 and column 2 value
$DBConnection->->table('users')->whereRaw("$val between col1 and col2")->get();
回答by mariordev
Your eloquent example using where() didn't work because you have the comparison operators reversed. If you want to retrieve rows where val is between col1 and col2, it should be like this:
您使用 where() 的雄辩示例不起作用,因为您将比较运算符颠倒了。如果要检索 val 在 col1 和 col2 之间的行,则应如下所示:
my_model::where('col1','<=',$val)->where('col2','>=',$val)
Notice the comparison operators are reversed to say "where val is greater than or equal to col1 and val is less than or equal to col2."
请注意,比较运算符被颠倒为“其中 val 大于或等于 col1 且 val 小于或等于 col2”。
You may have to squint a little hard to see it. :)
你可能不得不眯着眼睛看它。:)