将withCount添加到集合json

时间:2017-09-25 09:00:32

标签: json laravel eloquent

所以我有两个模型,Client和Project,而Client与项目有很多关系。我只是尝试将客户端的项目计数添加到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()方法加载此方法而不是每个方法?

2 个答案:

答案 0 :(得分:0)

来自Documentation

$clients = Client::withCount('projects')->get();

foreach ($clients as $client) {
    echo $client->projects_count;
}

答案 1 :(得分:0)

所以我设法自己解决了,虽然我确信他们必须是一个更好的方式。

<强> 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;
}