【问题标题】:Laravel filter date range with date range columnsLaravel 使用日期范围列过滤日期范围
【发布时间】:2021-02-07 21:21:31
【问题描述】:

如果所选日期($postFr、$postTo)在定义的时间段内,我想列出相关产品。那么我可以像下面的例子那样做吗?

示例:

$q->whereBetween('start_date', array($postFr, $postTo));
$q->orWhereBetween('end_date', array($postFr, $postTo));

//Could there be a similar use like this???;

$q->whereBetween(array(start_date, end_date), $postFr);
$q->orWhereBetween(array(start_date, end_date), $postTo);

详细解释:

我有一个像这样的周期表

periods

|  id  |  start_date  |  end_date  | product_id |   
|------|--------------|------------|------------|
|  1   | 2021-02-19   | 2021-03-21 |  1         |   
|  2   | 2021-02-19   | 2021-03-21 |  2         |   
|  3   | 2021-02-19   | 2021-03-21 |  3         |   
|  4   | 2021-02-19   | 2021-03-21 |  2         |   

我有一个这样的产品表

products

|   id  |   name    |
|-------|-----------|
|   1   |   pro1    |
|   2   |   pro2    |
|   3   |   pro3    |

我的模型页面相关代码如下

public $belongsTo = [
        'relationPeriod' => [
            'Model->periods table',
            'key' => 'id',
            'otherKey' => 'product_id',
        ]
 ]
 
 $query->whereHas('relationPeriod', function($q) use ($postFr, $postTo){
     $q->whereBetween('start_date', array($postFr, $postTo]));
     $q->orWhereBetween('end_date', array($postFr, $postTo));
 });

【问题讨论】:

  • array(start_date, end_date) 不是有效的 php
  • 你的第一行代码$q->whereBetween('start_date', array($postFr, $postTo]));你正在使用array() & ] 一起?
  • @Berto99 我知道,我问有没有这样的用途。
  • @bhucho 不,这是错误的。忽略。

标签: laravel eloquent


【解决方案1】:

有效

$q->whereDate('start_date', '<=', $postFr);
$q->whereDate('end_date', '>=', $postFr);
$q->orWhereDate('start_date', '<=', $postTo);
$q->whereDate('end_date', '>=', $postTo);

【讨论】:

    【解决方案2】:

    这将起作用:

    $start_date = '2021-01-01';
    $end_date = '2021-02-01';
    $filter = Atom_juice_data_history::whereBetween('created_at',[$start_date, $end_date])
                ->where('atom_juice_data_id',$product_id)
                ->orderBy('created_at', 'ASC')
                ->get();
    

    这是参考网址 https://medium.com/@sectheater/how-to-use-laravel-wherebetween-method-elegantly-20a50f3b0a2a

    【讨论】:

    • 这没有提供有效的答案。在 OP 中有一个日期范围 (start_date,end_date) 与输入日期范围 ($postFr, $postTo) 之间的比较。再次阅读问题
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2016-11-25
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多