doushi1957 2018-07-27 16:08
浏览 31
已采纳

Laravel 5.4 belongsToMany - 在html中显示结果

I create a many-to-many relationship, where many projects can be assigned to many users. My problem is that I do not know how to display projects assigned to a given user. . Currently, all available projects are displayed. I created pivot table, where after adding the project I store the project id and user id. This is my code:

User.php

 public function projects()
    {
        return $this->belongsToMany('App\Project')->withTimestamps();
    }

Project.php

 public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps();
    }

ProjectsController.php

public function projects()
    {
        $projects = Project::latest()->get();
        return view('pages.projects')->with('projects', $projects);
    }

migrations:

public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->longText('p_name')->nullable();
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('project_user', function (Blueprint $table) {
            $table->unsignedInteger('project_id');
            $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }
  • 写回答

1条回答 默认 最新

  • dtf54486 2018-07-27 16:24
    关注

    Eager load users in your controller:

    public function projects()
    {
        $projects = Project::latest()->with('users')->get();
        return view('pages.projects')->with('projects', $projects);
    }
    

    In your view:

    @foreach($projects as $project)
        @foreach($project->users as $user)
    
        @endforeach
    @endforeach
    

    If you want to display projects assigned to a user you would do something like:

    public function projectsByUser($userId)
    {
        $user = User::findOrFail($userId);
    
        $projects = $user->projects;
    
        return view('pages.projects')->with('projects', $projects);
    }
    

    and keep the view like:

    @foreach($projects as $project)
    
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 如何批量获取json的url
  • ¥15 对法兰连接元件所承受的表面载荷等效转化为法兰开孔接触面上的等效表面载荷?
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼