我有三个模特:
class Site extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function stats()
{
return $this->hasMany('App\Models\Stat');
}
}
class User extends Model
{
public function sites()
{
return $this->belongsToMany('App\Models\Site');
}
public function stats()
{
return $this->belongsToMany('App\Models\Stat');
}
}
class Stat extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User');
}
public function sites()
{
return $this->belongsTo('App\Models\Site');
}
}因此,有:
一个站点有一个统计信息列表,从这个列表中,用户可以拥有一些统计信息。

我试图得到所有的网站和前端网站,统计的统计为连接的用户。
现在我试着:
//repository
function getAll($user_id = 0)
{
$with = [];
$with['users'] = function ($query) use ($user_id) {
$query->where('id', '=', $user_id);
};
return Site::with($with)->orderBy('name')->get();
}
//controller
$sites = getAll($user_id);
//view
foreach($sites as $site){
$count_stats = $site->users->first()->stats->where('site_id',$site->id)->count();
}它可以工作,但并不是很优雅,它可以处理大量的sql请求,并且页面速度更慢。
你有更好的解决方案吗?
发布于 2016-02-15 11:43:51
如果站点有多个用户,并且站点有多个Stats,那么用户就有多个通过站点进行的统计。
修改User类:
public function stats() {
return $this->hasManyThrough('App\Stat', 'App\Site', 'user_id', 'site_id');
}急载:
$user = User::with('stats')->find($user_id);
$stats = $user->stats();另外,我认为你的统计应该belongsTo站点,因为站点hasMany统计。您还需要更改大量的belongsToMany,因为它们看起来使用不当。
https://stackoverflow.com/questions/35392347
复制相似问题