【问题标题】:Adding withCount to collection json将 withCount 添加到集合 json
【发布时间】:2017-09-25 09:00:32
【问题描述】:

所以我有两个模型,Client 和 Project,并且 Client 与项目有 hasMany 关系。我只是想将客户端的项目计数添加到 JSON 响应中,但我无法让它工作。

我的控制器只返回所有项目;

public function index(Client $client)
{
    return $client->all();
}

我的模型包含以下内容;

protected $appends  = ['client_projects_count'];


/**
 * Create a relationship between this client and it's projects
 */
public function clientProjects() {
    return $this->hasMany('App\Project');
}

public function getClientProjectsCountAttribute()
{
    return $this->withCount('clientProjects');
}

这只是将client_projects_count 添加到响应中,但它是一个空数组。我很接近,如果我 dd($this->withCount('clientProjects')->get()) 我可以看到 client_projects_count 的计数正确,但是如果我删除 dd 并保留 ->get() ,那么我会收到内部服务器错误。

另外,是否可以只为index() 方法而不是每个方法加载它?

【问题讨论】:

    标签: json laravel eloquent


    【解决方案1】:

    来自Documentation

    $clients = Client::withCount('projects')->get();
    
    foreach ($clients as $client) {
        echo $client->projects_count;
    }
    

    【讨论】:

    • 所以最后两行中的任何一行进入getClientProjectsCountAttribute? $client 来自哪里?我尝试将其更改为$this 并为$client-> 获取Call to undefined method Illuminate\\Database\\Query\\Builder::all(),并在最后一行获取return $client->withCount('projects')->get();
    • @KeironLowe 您需要 projectCount 用于一个客户还是客户列表?
    • 客户列表,我列出了所有客户并想添加客户拥有的项目数量
    • 我已经看到了,但我不确定这是否适合我的情况?当通过控制器中的index() 方法列出所有客户端时,如何应用它以便将计数添加到 JSON 中?
    【解决方案2】:

    所以我自己设法解决了这个问题,尽管我确信他们一定是更好的方法。

    Client.php

    protected $appends  = ['client_projects_count'];
    
    
    /**
     * Create a relationship between this client and it's projects
     */
    public function clientProjects() {
        return $this->hasMany('App\Project');
    }
    
    public function clientProjectsCount()
    {
        return $this->clientProjects()->selectRaw('client_id, count(*) as aggregate')->groupBy('client_id')->get();
    }
    
    public function getClientProjectsCountAttribute()
    {
        return isset($this->clientProjectsCount()[0]) ? $this->clientProjectsCount()[0]->aggregate : 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      • 2019-02-08
      相关资源
      最近更新 更多