[英]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.