拉拉维尔嵌套关系这些是我的关系我尝试过什么

2022-08-30 09:18:34

我很难让一个非常嵌套的关系在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 

这些是我的关系

事件模型

class Event extends Eloquent
{
    protected $table = 'events';

    public function city()
    {
        return $this->belongsTo('City');
    }
}

城市模式

class City extends Eloquent
{
    protected $table = 'cities';

    public function companies()
    {
        return $this->hasMany('Company');
    }

    public function event()
    {
        return $this->hasMany('Event');
    }
}

公司模式

class Company extends Eloquent {

    protected $table = 'companies';

    public function persons()
    {
        return $this->hasMany('Person');
    }

    public function city()
    {
        return $this->belongsTo('City');
    }
}

人物模型

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();
    }
}

我尝试过什么

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中实现这种嵌套关系链接有那么困难吗?

谢谢!


答案 1
return Event::with('city.companies.persons')->get();

如果只想从表中选择某些字段,请使用以下命令:persons

return Event::with(['city.companies.persons' => function ($query) {
    $query->select('id', '...');
}])->get();

答案 2

对于城市和公司的特定领域,你需要分发雄辩的。例如:

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();

推荐