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

时间:2019-02-15 10:34:12

标签: laravel eloquent eager-loading eloquent--relationship

我有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');
    }
}

2 个答案:

答案 0 :(得分: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;
    });

答案 1 :(得分: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);