【问题标题】:How to get Banks have High Number of branches first to Low Number of Branch after that In Laravel如何让银行在 Laravel 中先拥有大量分支机构,然后再拥有少量分支机构
【发布时间】:2020-10-14 21:21:03
【问题描述】:

我正在使用 Laravel Relation 列出我的银行分支机构和所有这些设置的层次结构如下所示

国家--hasMany->银行--hasMany->分行。

 $country = Country::where("iso2",  $this->app->request->route()->parameter('country'))->first();

这是国家模型中银行的关系代码:

public function banks()
{
    return $this->hasMany(Bank::class);
}

银行模型中的分行关系代码

 public function branches()
{
    return $this->hasMany(Branch::class);
}

现在我的动机是我只想让这个国家的 15 家银行成为可验证的,但条件是拥有大量分支机构的银行将在列表中排名第一。 您能否为我提供任何带有 laravel 雄辩查询的简单解决方案,这对我有很大帮助。

【问题讨论】:

  • 编辑并发布您的query 代码和您的问题,以便我们进行编辑

标签: php mysql laravel eloquent


【解决方案1】:

试试这个:

$banks = Bank::with(['branches'])
->map(function ($bank) {
    $bank->num_branches = $bank->branches->count();
    $bank;
})
->sortByDesc('num_branches')
->take(15);

【讨论】:

    【解决方案2】:

    大家好,我使用 withCount 的解决方案,这是我的解决方案查询

     $banks = Bank::where('country_id', $country->id)->withCount('branches')->having('branches_count', '>', 0)->orderBy('branches_count', 'DESC')->take(15)->get()->toArray();
    

    【讨论】:

      猜你喜欢
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 2012-04-20
      相关资源
      最近更新 更多