如何使用 eloquent 从两个 Has Many Relations 中获取一个值

How to use eloquent to get a value from two Has Many Relations

我遇到一个问题,一个配置文件可以包含多个活动以及多个位置。 这些活动通过枢轴 table 链接,但我的目标只是 return 所有位置 ID。

简介:

public function campaigns() {
   return $this->hasMany('App\Models\Campaign', 'profile_id', 'id');
}

活动:

  public function locations() {
     return $this->belongsToMany('App\Models\Location')->withPivot('campaign_id', 'location_id');
  }

目前我正在通过

解决这个问题
$campaigns = $profile->campaigns;

[Doing a nested foreach loop and placing each ID into the array]

我如何通过查询得到这个? 我试过了

 $campaigns = $profile->campaigns()
                        ->with('locations')
                        ->get()
                         ->pluck('location.id');

好吧,你的目标是从该位置获取信息,所以我将以此开始你的查询。您可以使用 whereHas() 方法根据关系调整查询。

这假设您的 Location 定义了 campaigns 关系,并且您的 Campaign 定义了 profile 关系。

$ids = Location::whereHas('campaigns.profile', function ($query) use ($profile) {
    return $query->where('id', $profile->id);
})->pluck('id');

您可以在 documentation here 中阅读有关按关系查询的更多信息。