laravel雄辩资料档案库查询外键表

w1e3prcc  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(118)

嗨,我正在使用一个自定义存储库,我对查询一个表来检索数据感到很舒服,如下所示:

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,我想使用登录用户检索这些表的记录,但我不确定如何构造我的查询,有人能提供指导吗?

qhhrdooz

qhhrdooz1#

根据laravel文档,在您的项目模型中,您可以添加以下函数:

class Project extends Eloquent
{
    public function clients()
    {
        return $this->hasMany(Client::class);
    }
}

然后,在客户端模型中,您可以添加与函数的反向关系:

class Client extends Eloquent
{
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}

然后,您可以使用如下函数检索数据:

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

相关问题