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

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

问题描述:

I have two tables in relation users and projects. In users table I have addiotional field admin_id.

Pivot table is project_user with columns: id, user_id, project_id and additonal field admin_id

When I selecting projects from database I need also to check if admin_id from pivot table is equal with admin_id from users table is it possible???

Here is my User modal:

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

Here is Controller:

 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

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

数据透视表是 project_user code>,其中包含以下列: id,user_id,project_id和 additonal field admin_id code> p>

当我从数据库中选择项目时,我还需要检查来自数据透视表 code>的 admin_id是 equal code> 使用 admin_id from users table code>是否可能??? p>

这是我的用户模式: p>

  public  function projects(){
返回$ this  - &gt; belongsToMany('App \ Project','project_user') - &gt; withPivot('admin_id'); 
} 
  code>  pre> 
  
 

这是Controller: p>

 公共功能项目(Project $ project){
 //采取项目形式当前ID 
 $ projects = User :: findOrFail  (Auth :: user() - &gt; id); 
 // NOT IMPORTANTE 
 $ users = User :: lists('name','id'); 
返回视图('projects',array('  projects'=&gt; $ projects,'users'=&gt; $ users)); 
} 
  code>  pre> 
 
 

Blade: p>

  @foreach($ projects  - &gt; 项目为$ project)
&lt; a href =“#”class =“list-group-item”&gt; {{$ project  - &gt;  name}}&lt; / a&gt; 
 @ endforeach 
  code>  pre> 
  div>

I found way....

This linke:

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

Should be changed with this:

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

Referring to this documentation should give you what you need: http://laravel.com/docs/5.0/eloquent#querying-relations

Specifically this section, which explains how you can add conditions to a relation query

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

})->get();