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

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名