【问题标题】:Eloquent Relationship in Laravel ManytoMany ThroughLaravel 多对多中的雄辩关系通过
【发布时间】:2017-08-03 19:15:21
【问题描述】:

我的 Laravel 项目中有三个类:CityCompanyactivity。所以,City 有很多 Company,而 Comapany 属于一个城市;然后我知道该公司可能有一项或多项活动;我要问的是我怎样才能在一个城市进行所有活动。

城市模型:

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

公司模式:

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

public function activities()
    {
        return $this->belongsToMany('App\Models\Activity');
    }

活动模型:

public function companies()
    {
        return $this->belongsToMany('App\Models\Company');
    }

感谢一切。 最好的问候。

【问题讨论】:

    标签: php laravel orm eloquent relationship


    【解决方案1】:

    您可以使用nested eager loading 加载包含所有公司和活动的城市模型:

    City::with('companies.activities')->find($cityId);
    

    如果您只想加载活动,可以使用whereHas() 方法:

    Activity::whereHas('companies', function($q) use($cityId) {
        $q->where('city_id', $cityId);
    })->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-03
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2018-10-27
      • 2018-03-28
      • 1970-01-01
      相关资源
      最近更新 更多