【问题标题】:Laravel 4, eloquent - between statement and operatorsLaravel 4,雄辩 - 语句和运算符之间
【发布时间】:2013-12-12 09:47:11
【问题描述】:

有一个我用来在 mysql 中运行的查询:

select * from my_table where $val between col1 and coL2;

它工作正常,但使用 laravel 4,进行该查询的唯一方法是使用类似

my_model::where('col1','>=',$val)->where('col2','<=',$val)

这种方式似乎行不通,因为我在使用通常的“select * ...”时没有相同的结果

有什么想法吗?

只是为了澄清我的要求: 在我的情况下,我没有“...... value1 和 value2 之间的列”但是“commun 之间的值” 所以在我看来我不能使用“中间”

【问题讨论】:

标签: php mysql laravel eloquent query-builder


【解决方案1】:

你可以试试这样的

// Get records whose id between 3 and 6
$users = User::whereBetween('id', array(3, 6))->get();

或者使用变量

$id = 'id';
$from = 1;
$to = 5;
$users = User::whereBetween($id, array($from, $to))->get();

这将获取所有ID15 之间的记录。

【讨论】:

  • 感谢您的回复。我的问题是查询中的输入数据必须在列之间。
  • 没看懂,能不能描述的更详细一点?
  • @WereWolf-TheAlpha 您正在硬编码“介于”值array(3,6),但他需要在表中的两列之间进行选择 -- SELECT * FROM table WHERE $desiredValue BETWEEN col1 AND col2
  • @TheAlpha $attendances= Attendance::whereBetween('attndate', array($fromdate, $todate))->get(); .....这个命令不适用于日期??还有其他比较日期的解决方案吗??
【解决方案2】:

应该这样做...

$results = my_model::select('*')-&gt;whereRaw("$val between col1 and coL2")-&gt;get();

我认为这很安全,但您可能需要先清理$val

【讨论】:

  • laravel 会帮你清理这个吗?
  • @Rafael, @user1669496,Laravel 不对变量做任何事情。您需要这样调用:$results = my_model::select('*')-&gt;whereRaw("? between col1 and coL2", ['someValue'])-&gt;get(); 进行安全查询。
【解决方案3】:

在不创建 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();

【讨论】:

    【解决方案4】:

    您使用 where() 的雄辩示例不起作用,因为您将比较运算符颠倒了。如果要检索 val 在 col1 和 col2 之间的行,应该是这样的:

    my_model::where('col1','<=',$val)->where('col2','>=',$val)
    

    请注意,比较运算符被反转为“val 大于或等于 col1 且 val 小于或等于 col2”。

    您可能需要稍微眯眼才能看到它。 :)

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2013-09-09
      • 2015-06-01
      相关资源
      最近更新 更多