列出所有项目并突出显示给定类别中的项目

时间:2019-04-09 09:20:01

标签: php eloquent relationship

所以...我得到了这两个雄辩的模型和一个数据透视表:

## Categories ##
- ID
- title
belongsToMany(Items)

## Items ##
- ID
- title
belongsToMany(Categories)

## Items_Categories ##
- items ID
- categories ID

我需要所有项目的列表,并突出显示给定类别中的项目。

# Example #

## Categorie #1 ##
- Item #1 (is in category)
- Item #2 
- Item #3 (is in category)
- Item #4 (is in category)
- Item #5

## Category #2 ##
- Item #1 (is in category)
- Item #2 
- Item #3
- Item #4 (is in category)
- Item #5

我觉得我过去做过一百次,但是我不知道该如何设置。 :-(

如果有更好的解决方案来设置我在玩的模型/关系,

// Get a single category with containing items
$category = Catgegory::whereNull('is_deleted')
    ->where('id', 1)
    ->with('items')
    ->first();

// Get all items
$allItems = Item::whereNull('is_deleted')
    ->get();


// Now what?
foreach ($allItems as $item) {
    // Compare with category items?!
}

1 个答案:

答案 0 :(得分:2)

您可以在项目模型中添加一个方法,以检查项目类别是否等于该类别。因此您可以像这样检查它:

项目模型中检查category_id的方法:

  public function isInCategory($category_id){

      //get all $category_ids
      $category_ids = $this->categories()->pluck('id')->toArray();

     //check if $category_id exists in $category_ids array
      if(is_array($category_ids) && in_array($category_id,$category_ids))
          return true;

      return false;

    }

或者您可以使用此方法完成

 public function isInCategory($category_id){

   return $this->categories->contains($category_id);
}

两种方法都可以正常工作。但是请记住在项目模型中编写此方法。

因此您可以像这样在代码中使用它:

// Get a single category with containing items
$category = Catgegory::whereNull('is_deleted')
    ->where('id', 1)
    ->with('items')
    ->first();

// Get all items
$allItems = Item::whereNull('is_deleted')
    ->get();


// check the category id
foreach ($allItems as $item) {
    $item->isInCategory($category->id) // returns true or false
}
相关问题