【问题标题】:One to many relationship in laravel5laravel5中的一对多关系
【发布时间】:2017-01-30 16:47:45
【问题描述】:

我必须表分支和协会, 而Branch table 与Association 是一对多的关系。 我已经完成了这两个模型中的关系。 现在我想获取与每个分支相关的关联数。 谁能解决我的问题?

【问题讨论】:

    标签: laravel model relationship one-to-many


    【解决方案1】:

    简单的方法

    你可以简单地使用

    $branch->associations()->count();
    


    更有效的方法

    更有效的方法如下,您可以在this github issue中找到:

    分支模型:

    public function associationCountRelation()
    {
        return $this->hasOne(Association::class)->select(DB::raw('id, count(*) as count'))->groupBy('id');
    }
    
    public function getAssociationCountAttribute()
    {
        return $this->associationCountRelation->count;
    }
    

    那么你可以这样使用它:

    $branch = Branch::with('associationCountRelation')->find($id);
    
    echo $branch->associationCount;
    

    【讨论】:

      【解决方案2】:

      如果您已经有模型并建立了关系。

      $branches=Branch::with('associations')->get();
      foreach($branches as $branch)
      {
            foreach($branch->associations as $association)
            {
                  print_r($associtaion->name);
            }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-15
        • 2018-09-27
        • 2011-03-30
        • 2023-01-16
        • 2015-09-20
        • 2018-03-16
        • 1970-01-01
        相关资源
        最近更新 更多