[英]Laravel - Relationships issue
我有3种型号:
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');
}
}
因此有:
站点具有统计信息列表,从该列表中,用户可以具有一些统计信息。
我正在尝试获取所有站点和foreach站点,已连接用户的统计数据。
目前我尝试了:
//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请求,并且页面速度较慢。
您有更好的解决方案吗?
如果站点有许多用户,并且站点具有许多统计信息,则用户通过站点具有许多统计信息
修改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();
另外,我觉得你应该Stat公司belongsTo
网站,因为网站hasMany
统计。 您还需要更改很多belongsToMany
,因为它们看起来使用不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.