代码之家  ›  专栏  ›  技术社区  ›  Sid Heart

如何修复此类别选择方法

  •  0
  • Sid Heart  · 技术社区  · 7 年前

    嗨,我只是想把我的电影博客分类,它的工作正常,但编辑类别必须选择正确。 所以我这样做了:

    //fetching all categories
    @foreach($categories as $category)
    
      //start option
      <option 
    
      //fetching current movie categories
      @foreach($movie->categories as $cat)
    
        //matching is this category match with
        @if($category->name === $cat->name)
    
        //if match selected method works
        selected="selected" 
    
        @endif
    
      @endforeach
    
      >{{ $category->name }}
    
      </option>
    @endforeach
    

    它工作得很好,但我认为这是一个错误的方式 你能给我推荐个好方法吗 谢谢

    2 回复  |  直到 7 年前
        1
  •  0
  •   Hasan Teymoori    7 年前

    请检查:
    @if(in_array( $category->name ,$movie->categories->pluck('name')) {{'selected' }} @endif

    如果给你一个 type arg2 must be an array error 。添加一个 toArray() 在采摘方法之后。

        2
  •  0
  •   FULL STACK DEV    7 年前

    我就是这么做的。

        <select class="form-control" name="category_id">
            @foreach($categories as $category)
                <option value="{{$category->id}}" {{ isset($gallery) && $category->id == $gallery->category_id?'selected':''}}>{{$category->name}}</option>
            @endforeach
        </select>
    

    可以使用三元运算符而不是 if() .

    如果你有多对多的关系,你可以尝试

    <select class="form-control" name="category_id">
            @foreach($categories as $category)
                <option value="{{$category->id}}"  {{$movie->categories->contains('name', $category->name )?'selected':'' @endif >{{$category->name}}</option>
            @endforeach
        </select>
    

    希望这有帮助。

    推荐文章