如何在 pivot table Laravel 中使用附加字段

How to use additional fields in pivot table Laravel

我有两个 table 与用户和项目有关。在用户 table 中我有附加字段 admin_id.

枢轴 table 是 project_user,列为:id, user_id, project_id and additonal field admin_id

当我从数据库中选择项目时,我还需要检查 admin_id from pivot table 是否为 equaladmin_id from users table 是否可能???

这是我的用户模式:

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

这是控制器:

 public function project(Project $project){
            //TAKING PROJECTS FORM CURRENT ID
            $projects = User::findOrFail(Auth::user() -> id) ;
            //NOT IMPORTANTE
            $users = User::lists('name','id');
            return view('projects',array('projects' => $projects,'users' => $users ));
        }

Blade:

@foreach($projects -> projects as $project)
<a href="#" class="list-group-item">{{ $project -> name }}</a>
@endforeach

参考此文档应该可以满足您的需求: http://laravel.com/docs/5.0/eloquent#querying-relations

特别是这一节,它解释了如何向关系查询添加条件

$posts = Post::whereHas('comments', function($q)
{
    $q->where('content', 'like', 'foo%');

})->get();

我找到方法了....

此链接:

$projects = User::findOrFail(Auth::user() -> id) ;

应更改为:

$projects = User::findOrFail(Auth::user() -> id)->projects()->where('admin_id', '=', $this->id)->get();