多对多的laravel获取值

时间:2018-01-27 20:24:05

标签: php mysql laravel

在用户类模型中,我有这个

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

在项目类模型中我有这个:

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

在我的projectController中我有这个:

    public function index()
{
    $TeamLeader = array();
    $posts = Project::orderby('id', 'desc')->with('users')->paginate(5); 
    return view('Projects.index', compact('posts'));
}

在我看来,每个人都有这个:

                    @foreach ($posts as $post)
                    <tr>
                        <td><input type="checkbox" class="checkthis" /></td>
                        <td href="{{ route('Projects.show', $post->project_id ) }}">{{ $post->project_id }}</td>
                        <td>{{ $post->name }}</td>
                        <td>{{ $post->description }}</td>
                        <td>{{ $post->created_at }}</td>
                        <td>{{ $user->name}}</td>
                        <td><p data-placement="top" data-toggle="tooltip" title="Show"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#show" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
                        <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
                    </tr>
                @endforeach

我的问题是,在我看来我无法获得用户名,但是realation是多对多但是我没有得到参与项目的用户的名字,数据库结构就像你想象的那样:

用户有id,name,......

项目有id,name,location,user_id,.....

很抱歉没有提及,但我也有这个共同的表:

        Schema::create('project_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('project_id')->unsigned();
        $table->integer('user_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('project_id')->references('id')->on('projects');

        $table->timestamps();
    });

1 个答案:

答案 0 :(得分:0)

实际上你的桌子设计并不多,一到多[用户有很多项目] 如果你想做多对多关系必须做一个中间表(数据透视表)

看看this
This is helpful

将此添加到您的迁移

Schema::create('project_user', function(Blueprint $table)
  {
      $table->integer('user_id')->unsigned()->nullable();
      $table->foreign('user_id')->references('id')
            ->on('users')->onDelete('cascade');

      $table->integer('project_id')->unsigned()->nullable();
      $table->foreign('project_id')->references('id')
            ->on('projects')->onDelete('cascade');

      $table->timestamps();
  });

project_user表是从相关模型名称的字母顺序派生而来的,包含user_id和project_id列
然后从项目表中删除user_id列

最后你可以访问像

这样的用户名
$project->users[0]->name
$project->users[0]->name