【问题标题】:Getting count of nested relationship with 'withCount' method使用'withCount'方法获取嵌套关系的计数
【发布时间】:2020-08-11 07:15:55
【问题描述】:

我需要帮助弄清楚如何让 withCount() 处理嵌套关系。

到目前为止我已经尝试过了

return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')->withCount('campaigns.users')->where($matchTheseThings)->get();

基本上,我想获取活动模型中的用户数。

CampaignsModel 上的关系如下所示:

public function users(){
    return $this->hasMany('App\UserPreferences', 'campaign_id', 'id');
}

与 CharityArea 中的活动的关系如下所示

public function campaigns(){
    return $this->hasMany('App\Campaigns', 'charity_area_id', 'id');
}

Laravel 抛出错误,提示找不到“campaigns.users”。

还有其他方法可以做到这一点吗?

谢谢。

【问题讨论】:

  • 您能否在您的CharityAreaModel 中分享campaigns() 关系?
  • 当然,我已经更新了帖子。谢谢

标签: php laravel eloquent


【解决方案1】:

您可以首先在 CharityArea 模型中设置一个 ManyThrough 关系。


    function users()
    {
        return $this->hasManyThrough('App\UserPreferences', 'App\Campaigns');
    }

那你可以拨打withCount()就可以了:


    return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')
        ->withCount('users')
        ->where($matchTheseThings)
        ->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2019-11-17
    • 2020-11-22
    • 2022-01-03
    • 2020-09-02
    • 2021-05-22
    • 2019-09-23
    相关资源
    最近更新 更多