Laravel嵌套关系 [英] Laravel nested relationships
本文介绍了Laravel嵌套关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多难以让非常嵌套的关系在laravel中正常工作。
I'm having a lot of trouble getting a very-nested relationship to work correctly in laravel.
想要的行为是
我按ID选择活动,我想查看哪些人订阅了活动。
现在的问题是在事件和人之间有一些表格。
I select an event by ID and i want to see which persons are subscribed to it. Now the problem is there are some tables between the event and the person..
这是可以工作的查询!
select
persons.id, persons.firstname, persons.lastname, event_scores.score
from
events
join
cities on cities.id = events.city_id
join
companies on cities.id = companies.city_id
join
persons on companies.id = persons.company_id
join
event_scores on event_scores.person_id = persons.id
where
event_scores.event_id = 1
group by
persons.id
这些是我的关系
事件模型
These are my relations
Event Model
class Event extends Eloquent
{
protected $table = 'events';
public function city()
{
return $this->belongsTo('City');
}
}
城市模型
City Model
class City extends Eloquent
{
protected $table = 'cities';
public function companies()
{
return $this->hasMany('Company');
}
public function event()
{
return $this->hasMany('Event');
}
}
公司模式
Company Model
class Company extends Eloquent {
protected $table = 'companies';
public function persons()
{
return $this->hasMany('Person');
}
public function city()
{
return $this->belongsTo('City');
}
}
人模型
b $ b
Person Model
class Person extends Eloquent
{
protected $table = 'persons';
public function company()
{
return $this->belongsTo('Company');
}
public function eventscore()
{
return $this->belongsToMany('Event', 'event_scores', 'person_id', 'event_id')
->withPivot('score')
->withTimestamps();
}
}
我尝试了
What I have tried
return Event::with('city')->with('company')->get();
和
return Event::with('city')
->whereHas('companies', function($query) use ($company_id){
$query->where('company_id', $company_id);
})->get();
和许多其他的可能性,我真的坚持这一点。在laravel中难以实现这种嵌套关系链接?
And many other possibilities, I'm really stuck on this. Is it so difficult in laravel to achieve this kind of nested relationship linking?
谢谢!
推荐答案
return Event::with('city.companies.persons')->get();
如果您只想从 persons
table,请使用:
If you only want to select certain fields from the persons
table, use this:
return Event::with(['city.companies.persons' => function ($query) {
$query->select('id', '...');
}])->get();
这篇关于Laravel嵌套关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文