douqipi9704 2019-04-09 09:20
浏览 32
已采纳

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

So ... I got those two eloquent models and a pivot table:

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

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

## Items_Categories ##
- items ID
- categories ID

I need a list of ALL items and highlight those which are in a given category.

# 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

I feeld like I did this a hundred times in the past, but I can't figure out how to set this up. :-(

If there's a better solution on setting up those models / relationships I'm game.

// 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条回答 默认 最新

  • dongtan9518 2019-04-09 09:37
    关注

    You can add a method in items model to check whether is item category equals to that category or not. so you can check it like so:

    The method in the item model that checks the 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;
    
        }
    

    Or you can do it with this method

     public function isInCategory($category_id){
    
       return $this->categories->contains($category_id);
    }
    

    Both methods are working fine. But remember to write this method in Item model.

    So you can use it in your code like this:

    // 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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录