【问题标题】:How to use a Form::Select with a Pivot Table in Laravel 5.6如何在 Laravel 5.6 中使用 Form::Select 和数据透视表
【发布时间】:2018-12-02 19:54:18
【问题描述】:

我尝试在 Laravel 5.6 中使用 Form::select,但是当我进入编辑页面时,在选择中,有选项包含对象模型的所有数据,而不是常规字段。

我有一个游戏模型,它与标签模型之间存在多对多关系。

在游戏控制器的编辑功能中

public function edit($item)
{        
    $tags  = Tag::all();
    return view('megadmin.games.edit', compact('item', 'tags'));
}

在我的表单刀片中:

 {!! Form::select('tags', $tags, array_pluck($tags, 'id_tag','name'), ['class' => 'form-control'])!!}

结果如下:

The result

我只想要一个带有数据的普通选择/选项,并且我想在游戏表单中检索与游戏关联的模型标签。

谢谢你的帮助^^

【问题讨论】:

    标签: laravel forms select pivot-table


    【解决方案1】:

    我假设你正在使用 Form 模型绑定,所以你可以这样做:

    在您的游戏模型中创建一个仅为您的表单模型绑定的新方法:

    class Game extends Model
    {
      use FormAccessible;
    
      public function tags()
      {
         return $this->belongsToMany(Tag::class);
      }
    
      public function formTagsAttribute()
      {
        return $this->tags()->pluck('id_tag');
      }
    }
    

    在您的控制器中:

    public function edit($item)
    {        
        $tags  = Tag::pluck('name', 'id_tag');
        return view('megadmin.games.edit', compact('item', 'tags'));
    }
    

    在你看来:

    {!! Form::model($game, [$attributes]) !!}
        {!! Form::select('tags', $tags, null, ['class' => 'form-control']) !!}
         .
         .
         .
     {!! Form::close() !!}
    

    【讨论】:

      【解决方案2】:

      控制器

      public function edit($item)
      {        
          $tags  = Tag::all();
          $goodTag = $item->tags()->first()->id; 
           //here assuming `$item` is your Game object and 
          //you have ManyToMany relation with tags with `tags` function in game model 
         //lots of assuming
      
          return view('megadmin.games.edit', compact('item', 'tags', 'goodTag));
      }
      

      查看

       {!! Form::select('tags', array_pluck($tags,'name', 'id_tag'), $goodTag, ['class' => 'form-control'])!!}
      

      这里是laravel表单选择源代码https://github.com/illuminate/html/blob/master/FormBuilder.php#L393

      array_pluckhttps://laravel.com/docs/5.6/helpers#method-array-pluck

      【讨论】:

      • 它有效,但仍然存在两个问题:1)我在控制器中提供了两个标签对象,使用方法 Tag::all() 获取,并且在我的选择中只有一个 2)之间有联系我的游戏和标签(我有一个数据透视表 game_tag)并且没有选择好的标签。
      • 你还没有提到数据透视表,用数据透视表更新你的问题
      • 您仍然没有更新您的关系,但基于假设我已经更新了答案。你可以看看。选定的值是 `Form::select(` 的第三个参数,它对我有用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多