简体   繁体   English

Laravel-关系问题

[英]Laravel - Relationships issue

I have 3 models: 我有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');
    }
}

So there are : 因此有:

  • a many to many relation between sites and users 网站和用户之间的多对多关系
  • a many to many relation between users and stats 用户与统计信息之间的多对多关系
  • a one to many relation between site and stats 网站与统计资料之间的一对多关系

A site have a list of stats and from this list, an user can have some stats. 站点具有统计信息列表,从该列表中,用户可以具有一些统计信息。

在此输入图像描述

I'm trying to get all sites and foreach site, count of stats for the connected user. 我正在尝试获取所有站点和foreach站点,已连接用户的统计数据。

For the moment i tried : 目前我尝试了:

//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();
}

It works but it is not very elegant, it does a lot of sql requests and the page is slower. 它可以工作,但不是很优雅,它执行许多sql请求,并且页面速度较慢。

Do you have a better solution ? 您有更好的解决方案吗?

If Sites have many Users, and Sites have many Stats, then a User has many Stats through Site 如果站点有许多用户,并且站点具有许多统计信息,则用户通过站点具有许多统计信息

Modify User class: 修改User类别:

public function stats() {
    return $this->hasManyThrough('App\Stat', 'App\Site', 'user_id', 'site_id');
}

Eager load: 热切的负荷:

$user = User::with('stats')->find($user_id);
$stats = $user->stats();

Also, I think your Stat should belongsTo Site, since Site hasMany Stat. 另外,我觉得你应该Stat公司belongsTo网站,因为网站hasMany统计。 You need to change a lot of the belongsToMany as well since they look incorrectly used. 您还需要更改很多belongsToMany ,因为它们看起来使用不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM