【问题标题】:How to get today's all orders by restaurant in laravel?如何在laravel中按餐厅获取今天的所有订单?
【发布时间】:2021-11-13 15:12:21
【问题描述】:

我正在尝试从一家餐厅获得今天的订单。这是我的表结构

      restaurants
            id - integer
            name - string

        categories
            id - integer
            restaurant_id- foreign
            name - string

        items
            id - integer
            category_id - foreign
            name - string

        orders
            id - integer
            amonut- double

        order_items (pivot table)
            id - integer
            order_id - foreign
            item_id - foreign

这是我的餐厅模型

public function restaurant_categories() {
    return $this->hasMany(Category::class, 'restaurant_id')->orderBy('created_at', 'DESC');
}

public function restaurant_items() {
    return $this->hasManyThrough(Item::class, Category::class, 'restaurant_id', 'category_id')->with('category', 'item_assets')->orderBy('created_at', 'DESC');
}

这是我的物品模型

  public function orders(){
    return $this->belongsToMany(Order::class,'order_items','item_id', 'order_id' )
    ->withPivot('quantity','price');
 }

通过这段代码,我可以得到特定餐厅的所有订单

 $restaurant = Restaurant::with('restaurant_items')->find($id);
 $orders = [];
 foreach ($restaurant->restaurant_items as $item) {
    $orders[] = $item->orders;
  }

但是现在,我如何以及在哪里添加 where 条件以仅获取今天的订单?还有,如果我想获得特定日期的订单,那该怎么办?L

【问题讨论】:

    标签: mysql laravel eloquent relationship


    【解决方案1】:

    对于 Laravel 5.6+ 版本,您只需添加 whereDate() 条件

    $restaurant = Restaurant::with('restaurant_items')
         ->whereDate('created_at', Carbon::today())->get();
    

    或者你也可以使用 whereRaw()

    $restaurant = Restaurant::with('restaurant_items')
        ->whereRaw('Date(created_at) = CURDATE()')->get();
    

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多