Laravel 与 withCount() 有很多关系
Laravel hasmany relationship with withCount()
试图显示属于公司 table 的用户数 table 我只得到 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->getUser 时,我得到了 json 个用户,但是 withCount returns 总是 NULL。
在变量名中使用 underscore
而不是 camelCase
。
@foreach($allCompanies as $theCompany)
{{ $theCompany->get_user_count }}
@endforeach
更改代码
$allCompanies = Companies::withCount('getUser')->get();
至
$allCompanies = Companies::with ('getUser')->withCount('getUser')->get();
试图显示属于公司 table 的用户数 table 我只得到 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->getUser 时,我得到了 json 个用户,但是 withCount returns 总是 NULL。
在变量名中使用 underscore
而不是 camelCase
。
@foreach($allCompanies as $theCompany)
{{ $theCompany->get_user_count }}
@endforeach
更改代码
$allCompanies = Companies::withCount('getUser')->get();
至
$allCompanies = Companies::with ('getUser')->withCount('getUser')->get();