【问题标题】:show data select option by user in laravel在 laravel 中按用户显示数据选择选项
【发布时间】:2019-03-12 19:57:48
【问题描述】:

我想通过指定用户登录在选择选项中显示项目数据。

这是我的表单选择选项

<div class="form-group">          
  <label for="">Project *</label>        
    <select class="form-control select2" style="width: 100%;" name="project_id">
      <option value="project_id" selected>Select One</option>
         @foreach($projects as $id => $project)
           <option value="{{$id}}">{{$project}}</option>
         @endforeach
    </select>
</div>

这是我的控制器通过分配用户来提取项目名称

$projects = UserProjects::pluck('project_id', 'user_id');

我使用Many To Many Relation

在我的用户模型中

public function projects()
    {
        return $this->belongsToMany(Project::Class, 'user_projects');
    }

在我的项目模型中

public function users()
{
    return $this->belongsToMany(User::class, 'user_projects');
}

在我的表中枢轴user_projects 它只是project_iduser_id。我应该在表单的选择选项中写什么?

【问题讨论】:

  • 您要显示所有项目还是只显示已附加到用户的项目?
  • 仅显示基于分配用户的项目。例如当作为用户 A 输入时,则选择选项仅显示使用 A 完成的项目列表

标签: laravel model pivot-table relationship select-options


【解决方案1】:

many to many relation 中,您不必为中间表 (user_projects) 定义模型。

控制器

$user_projects = auth()->user()->projects;

查看

<div class="form-group">          
  <label for="">Project *</label>        
    <select class="form-control select2" style="width: 100%;" name="project_id">
      <option value="project_id" selected>Select One</option>

      @foreach($user_projects as $user_project)
           <option value="{{$user_project->id}}">{{$user_project->name}}</option>
      @endforeach

    </select>
</div>

【讨论】:

  • 任何错误Cannot declare class App\Models\User, because the name is already in use
  • 那是什么?你为什么要创建一个新的User Model
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多