【问题标题】:Laravel - whenLoaded() and count() on ResourceLaravel - 资源上的 whenLoaded() 和 count()
【发布时间】:2019-10-04 20:18:18
【问题描述】:

我有一个包含资产的集合的模型。

我希望使用集合资源返回资产计数,但结果会导致调用 whenLoaded 函数,从而加载集合中的所有资产。我不希望这种情况发生。

我不知道如何着手创建一个解决方案,该解决方案将继续允许我使用资源、计算资产,但不能调用 whenLoaded 函数。

return [
        'id' => $this->id,
        'name' => $this->name,
        'description' => $this->description,
        'enabled' => $this->enabled,
        'sticky' => $this->sticky,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'asset_count' => $this->assets->where('enabled', 1)->count(),
        'assets' => Asset::collection($this->whenLoaded('assets')),
 ];

有没有办法仍然使用资源,返回资产计数,但没有调用 whenLoaded 作为结果?

【问题讨论】:

  • 你可以试试$this->assets()->where('enabled', 1)->count(),它不应该以这种方式加载关系

标签: php laravel laravel-5


【解决方案1】:

试试这个

你可以简单地创建一个新的关系,比如liveassets

function liveassets(){
 return $this->hasMany('assets')->where('enabled','=', 1);
}

return [
    'id' => $this->id,
    'name' => $this->name,
    'description' => $this->description,
    'enabled' => $this->enabled,
    'sticky' => $this->sticky,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
    'asset_count' => $this->liveassets->count(),
    'assets' => $this->liveassets,
];

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 2020-09-11
    • 2018-03-07
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多