2014-09-02 188 views
0

您好我使用的是定製的倉庫,我得到舒服查詢一個表像這樣檢索數據:laravel雄辯庫查詢外鍵的表

public function getAll() 
{ 
// get all logged in users projects order by project name asc and paginate 9 per page 
return \Auth::user()->projects()->orderBy('project_name', 'ASC')->paginate(9); 

}

,並在我的控制,我只是調用

public function __construct(ProjectRepositoryInterface $project) { 

    $this->project = $project; 

} 

public function index() 
    { 
     $projects = $this->project->getAll(); 
     echo View::make('projects.index', compact('projects'));   
    } 

和我的看法是像這樣:

@if (Auth::check()) 
@if (count($projects) > 0) 
@foreach ($projects as $project) 
{{ $project->project_name }} 
@endforeach 
@else 
    <p>No records, would you like to create some...</p> 
@endif 
{{ $projects->links; }} 
@endif 

但是在我的項目表中,我有一個status_id和一個client_id,我想用已登錄的用戶檢索這些表的記錄,但我不知道如何構建我的查詢,有沒有人有任何指導?

回答

1

按照laravel [文件] http://laravel.com/docs/eloquent#relationships,在項目模型,你可以添加以下功能:

class Project extends Eloquent { 

public function clients() 
{ 
    return $this->hasMany('Client'); 
} 

}

在您的客戶端模式,那麼你可以添加具有關係的逆功能:

class Client extends Eloquent { 

public function project() 
{ 
    return $this->belongsTo('Project'); 
} 

}

然後,您可以使用以下功能檢索數據:

$clients = Project::find(1)->clients;