Mig*_*ens 34 php mysql database laravel
我在使用非常嵌套的关系在laravel中正常工作时遇到了很多麻烦.
想要的行为如下,
我按ID选择一个事件,我想看看哪些人订阅了它. 现在问题是事件和人之间有一些表格.
这是有效的查询!
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
Run Code Online (Sandbox Code Playgroud)
class Event extends Eloquent
{
protected $table = 'events';
public function city()
{
return $this->belongsTo('City');
}
}
Run Code Online (Sandbox Code Playgroud)
class City extends Eloquent
{
protected $table = 'cities';
public function companies()
{
return $this->hasMany('Company');
}
public function event()
{
return $this->hasMany('Event');
}
}
Run Code Online (Sandbox Code Playgroud)
class Company extends Eloquent {
protected $table = 'companies';
public function persons()
{
return $this->hasMany('Person');
}
public function city()
{
return $this->belongsTo('City');
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
return Event::with('city')->with('company')->get();
Run Code Online (Sandbox Code Playgroud)
和
return Event::with('city')
->whereHas('companies', function($query) use ($company_id){
$query->where('company_id', $company_id);
})->get();
Run Code Online (Sandbox Code Playgroud)
还有很多其他的可能性,我真的坚持这个.在laravel中实现这种嵌套关系链接是否如此困难?
谢谢!
Jos*_*ber 77
return Event::with('city.companies.persons')->get();
Run Code Online (Sandbox Code Playgroud)
如果您只想从persons
表中选择某些字段,请使用:
return Event::with(['city.companies.persons' => function ($query) {
$query->select('id', '...');
}])->get();
Run Code Online (Sandbox Code Playgroud)
Ras*_*aya 17
对于城市和公司特定领域,您需要分发具有说服力的人.例如:
return Event::with([
'city' => function ($query) {
$query->select('id', '...');
},
'city.companies' => function ($query) {
$query->select('id', '...');
},
'city.companies.persons' => function ($query) {
$query->select('id', '...');
}
])->get();
Run Code Online (Sandbox Code Playgroud)
小智 7
return Event::with(['city:id,name', 'city.companies:id,name', 'city.companies.persons:id,name'])->get();
Run Code Online (Sandbox Code Playgroud)
请注意,在嵌套级别(至少是中级)中,您还必须指定 FK 到父关系,否则您将获得该嵌套关系的空集合!我花了几个小时才弄清楚这一点。
小智 5
对于事件模型中的两级\xd8\x8c
\npublic function cities()\n{\n return $this->belongsToMany(City::class)->with('companies');\n}\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
35397 次 |
最近记录: |