【问题标题】:Laravel Eloquent get all categories of restaurants?Laravel Eloquent 获取所有类别的餐厅?
【发布时间】:2018-09-07 09:27:08
【问题描述】:

我正在尝试获取所有类别的餐厅。

我的模型:

餐厅

public function categories()
{
    return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id');
}

类别

public function restaurants()
{
    return $this->belongsToMany(Restaurant::class,'restaurant_categories_relation', 'category_id');
}

在我的控制器中:

$restaurants = Restaurant::where('district_id', $request->district)->paginate(8);
$categories = $restaurants-> ????;

请帮我做,谢谢!

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    您可以使用 has() 之类的:

    Category::has('restaurants')->get();
    

    这将返回与restaurants 相关的categories


    也尝试使用whereHas like :

    $users = Category::whereHas('restaurants', function($q){
        $q->->where('district_id', $request->district)->paginate(8);
    })->get();
    

    由于您已经是 Collection,我们无法查询类别,因此我建议在 Restaurant 模型内添加一个函数来范围,例如:

    public static function getCategoriesOfRestaurants($restaurants)
        $categories = [];
    
        foreach($restaurants as $restaurant){
          array_push( $categories, $restaurant->categories->pluck('id')->toArray());
        }
    
        return Category::WhereIn('id', array_unique($categories))->get();
    }
    

    然后在获得$restaurants 集合时调用它:

    $restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
    $categories  = Restaurant::getCategoriesOfRestaurants($restaurants);
    

    注意: 获取集合时使用with("categories") 将查询第一个查询中的所有相关类别,因此foreach 循环不会生成任何额外的查询,只是循环遍历已经获取的数据,最后我们会在return语句中得到类别的集合。

    【讨论】:

    • 谢谢,但 $restaurants 是从 where 子句中获取的集合。
    • 那么你想获取$restaurants集合的相关分类吗?
    • 是的,我想要那个!
    【解决方案2】:

    使用 with() 方法进行预加载,让您在单个查询中获取所有类别

    $restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
    foreach($restaurants as $restaurant){
      foreach($restaurant->categories as $category)
         {{$category}}
      }
    }
    

    如果您想在循环之外使用类别,则将这些类别分配给一个变量

    foreach($restaurants as $restaurant){
      $categories = $restaurant->categories;
    }
    
    // do something with $categories
    

    【讨论】:

    • 谢谢!但我想显示循环之外的所有类别。
    • 谢谢,但是如果我有很多餐馆,我想这个脚本会很慢!
    • @justcntt 有趣
    【解决方案3】:

    你的关系应该是 Restruant.php

    public function categories() {
        return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id','category_id');
    }
    

    然后在你的控制器方法中写 $restruants = Restruant::with('categories')->get();

    它应该返回你所有相关类别的所有restruants的集合。

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多