如何通过数据透视表从相关表中获取数据?

问题描述 投票:1回答:2

我有4个表:国家,活动,country_activities和包。国家和活动通过数据透视表country_activity相关,而包与country_activity相关。现在,我如何急切加载与一个国家/地区的每项活动相关的所有套餐?

class Country extends Model
{
    public function activities() {
        return $this->belongsToMany('App\Models\Activity','country_activities')->using('App\Models\CountryActivity')->as('country_activities');
    }
}

class Activity extends Model
{
    public function countries() {
        return $this->belongsToMany('App\Models\Country','country_activities')->using('App\Models\CountryActivity')->as('country_activities');
    }
}

class Package extends Model
{
    public function country_activities() {
        return $this->belongsToMany('App\Models\CountryActivity');
    }
}

class CountryActivity extends Pivot
{
    protected $table = 'country_activities';

    public function packages() {
        return $this->hasMany('App\Models\Package');
    }
}
laravel eloquent eager-loading eloquent--relationship
2个回答
0
投票

我在一个项目中做了类似的事情。我不确定它会起作用但值得拍摄:

$country = Country::find(1);
$country->activities = $contry->activities()->get()->each(function ($i, $k){
    $i->packages = $i->pivot->packages;
    //$i->makeHidden('pivot'); -> This is useful if you want to hide the pivot table
});
var_dump($country);

1
投票

所以,这对我有用。

   class Country extends Model
   {
        public function activities() {
        return $this->belongsToMany('App\Models\Activity','country_activities')->using('App\Models\CountryActivity')->withPivot(['id'])->as('country_activities');
   }

现在,在我的控制器中,我这样做

    $country = Country::with(['activities'=> function($q) {$q->where('name','Trekking');}])->where('name','Nepal')->first(['id','name']);
    $country->activities->map(function ($i){
        $i->country_activities->load('packages');
        return $i;
    });
© www.soinside.com 2019 - 2024. All rights reserved.