【问题标题】:laravel eloquent repository query foreign key tableslaravel eloquent 仓库查询外键表
【发布时间】:2014-09-02 21:57:34
【问题描述】:

您好,我正在使用自定义存储库,并且我习惯于查询一个表来检索数据,如下所示:

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,我想用已登录的用户检索这些表的记录,但我不知道如何构造我的查询,有人有任何指导吗?

【问题讨论】:

    标签: php laravel eloquent foreign-key-relationship


    【解决方案1】:

    根据 laravel [documentation]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;
    

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 2016-09-30
      • 2021-09-25
      • 2021-04-19
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2019-07-21
      相关资源
      最近更新 更多