[英]laravel returning relationships with eloquent and laravel
In my database I am an organisations table this table has the following relationships, 在我的数据库中,我是一个组织表,该表具有以下关系,
Many-to-many with users Many-to-many with clients One-to-many with projects 与用户多对多与客户多对多与项目一对多
In turn these relationships have other relationships for example projects 这些关系又具有其他关系,例如项目
One-to-one with client 与客户一对一
In my controller I am doing the following, 在我的控制器中,我正在执行以下操作:
$organisation = Organisation::all();
$organisation->load('users');
$organisation->load('clients');
$organisation->load('teams');
$organisation->load('projects');
return Response::json($organisation, 200);
So get all the organisations and there relational data. 因此,获取所有组织以及相关数据。
However what I wanting to do is also get the relationships of relationships, so for example get the client that is related to each project that an organisation has? 但是,我还想获得关系的关系,例如获得与组织具有的每个项目相关的客户? I thought that doing what I am doing would have worked but obviously not. 我认为做我想做的事会奏效,但显然没有。
Here are my models, 这是我的模特,
Organisation, 组织,
class Organisation extends Eloquent {
//Organsiation __has_many__ users (members)
public function users()
{
return $this->belongsToMany('User')->withPivot('is_admin');
}
//Organisation __has_many__ clients
public function clients()
{
return $this->belongsToMany('Client');
}
//Organisation __has_many__ projects
public function projects()
{
return $this->belongsToMany('Project');
}
} }
Projects 专案
class Project extends Eloquent { 类Project扩展了口才{
protected $fillable = [
'name',
'description',
'total_cost',
'start_date',
'finish_date',
'sales_person',
'project_manager',
'client_id',
'organisation_id',
'user_id'
];
public function organisations()
{
return $this->belongsToMany('Organisation');
}
public function salesperson() {
return $this->belongsTo('User', 'sales_person');
}
public function clients() {
return $this->belongsTo('Client', 'client_id');
}
} }
Clients 客户群
class Client extends Eloquent {
public function organisations()
{
return $this->belongsToMany('Organisation');
}
public function users()
{
return $this->belongsToMany('User');
}
public function projects()
{
return $this->hasMany('Project');
}
}
Have you tried: 你有没有尝试过:
$organisations = Organisation::with('projects', 'projects.clients')->all();
foreach($organisations as $organisation) {
foreach($organisation->projects as $project) {
foreach($project->clients as $client) {
echo $client->name;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.