如何在数据透视表Laravel中使用其他字段

时间:2015-03-19 14:21:04

标签: php mysql laravel-5

我在关系用户和项目中有两个表。在用户表中,我有addiotional字段admin_id

数据透视表为project_user,其列为id, user_id, project_id and additonal field admin_id

当我从数据库中选择项目时,我还需要检查admin_id from pivot table equal是否admin_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 ));
        }

刀片:

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

2 个答案:

答案 0 :(得分:0)

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

特别是本节,介绍如何为关系查询添加条件

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

})->get();

答案 1 :(得分:0)

我找到了......

这个linke:

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

应该改变:

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