Laravel与withCount()有很多关系

时间:2018-04-04 01:13:00

标签: laravel relationships

尝试显示属于公司表的用户表的计数我只获得NULL,而我可以在直接调用关系时看到正确的结果。这是显示代码:

@foreach($allCompanies as $theCompany)
{{ $theCompany->getUser_count }}
@endforeach

以下是模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Companies extends Model {
    protected $table = 'companies'; 

    public function getUser(){
        return $this->hasMany('App\User', 'company_id');
    }
}

这是控制器:

$allCompanies   = Companies::withCount('getUser')->get();

当我调用$ theCompany-&gt; getUser时,我得到一个json的用户,但是withCount返回的总是NULL。

2 个答案:

答案 0 :(得分:0)

在变量名中使用underscore而不是camelCase

@foreach($allCompanies as $theCompany)
    {{ $theCompany->get_user_count }}
@endforeach

答案 1 :(得分:0)

更改代码

$allCompanies   = Companies::withCount('getUser')->get();

$allCompanies   = Companies::with ('getUser')->withCount('getUser')->get();