【问题标题】:Laravel/Eloquent - How to query a for a relation that depends on another relationLaravel/Eloquent - 如何查询依赖于另一个关系的关系
【发布时间】:2022-01-02 18:43:01
【问题描述】:

我要写的查询:

我有三个模型:

  • 一个Chef有很多FoodItems。
  • 一个FoodItem有很多FoodItemAvailabilityDays

在我的查询中,我想通过给定的蛞蝓查找厨师。我想退回所有在特定日期可用的厨师食品。

示例:

想象一下厨师与蛞蝓“鲍勃史密斯”销售三种食品:千层面、汉堡和墨西哥卷饼。

  1. 千层面供应时间为 2022-01-01 和 2022-01-02
  2. 汉堡将于 2022 年 1 月 2 日发售
  3. 墨西哥卷饼于 2022-01-03 供应

如果我传入 slug "bob-smith" 和日期 "2022-01-02"

那么查询应该返回带有 Lasange 和 Burger 食品的“bob-smith”厨师。

模型关系:

// Chef.php
class Chef extends Model
{
  public function foodItems()
  {
    return $this->hasMany(FoodItem::class);
  }
}
// FoodItem.php
class FoodItem extends Model
{
  public function availabilityDays()
  {
    return $this->hasMany(FoodItemAvailabilityDay::class);
  }
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我找到了答案

    $chef = Chef::where('slug', $slug)
          ->with(['foodItems' => function ($food_item_query) use ($selected_date) {
            $food_item_query->whereHas('availabilityDays', function ($day_query) use ($selected_date) {
              $day_query->where('date', $selected_date);
            });
          }])
          ->firstOrFail();
    

    【讨论】:

      【解决方案2】:

      您应该像这样在ChefFoodItemAvailabilityDays 之间定义a HasManyThrough relationship

      class Chef extends Model
      {
        public function foodItems()
        {
          return $this->hasMany(FoodItem::class);
        }
      
        public function foodItemAvailabilityDays()
        {
          return $this->hasManyThrough(FoodItemAvailabilityDays::class, Chef::class);
        }
      }
      
      class FoodItem extends Model
      {
        public function chef()
        {
          return $this->belongsTo(Chef::class);
        }
      
        public function availabilityDays()
        {
          return $this->hasMany(FoodItemAvailabilityDay::class);
        }
      }
      
      class FoodItemAvailabilityDay extends Model
      {
        public function foodItems()
        {
          return $this->belongsTo(FoodItem::class);
        }
      }
      

      现在可以直接查询关系了:

      $chef = Chef::whereSlug($slug)
          ->with(['foodItemAvailabilityDays' => fn($q) => $q->where('date', $selectedDate)])
          ->firstOrFail();
      

      【讨论】:

        猜你喜欢
        • 2013-10-03
        • 2017-07-19
        • 2014-10-31
        • 2019-02-15
        • 2021-09-25
        • 2015-01-21
        • 2017-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多