【问题标题】:Laravel multiple models relationship return countLaravel 多模型关系返回计数
【发布时间】:2014-10-15 17:33:39
【问题描述】:

我有三个模型:

用户:

public function projects()
{
    return $this->hasMany('StoredFile', 'user_id', 'id')->with('files');
}

存储文件:

public function files()
{
    return $this->hasMany('File', 'hash', 'user_hash');
}

和没有关系方法的文件模型

问题:

我使用下面这段代码来获取项目和每个项目存储的文件:

$projects = $user->projects;
var_dump(json_encode($projects))
// {"project_name":"test","user_hash":"64650458b6Fhgd68ca57308222","files":[{"id":1,"name":"example.pdf"}]}

我可以使用 count($projects[0]->files) 来获取文件数

但是这个 $projects 变量需要通过 Response::json 返回到客户端

return Response::json($project);

而且我不能将文件泄露给访问者,我想修改 StoredFile 模型以仅返回文件数

就像:

return $this->hasMany('File', 'hash', 'user_hash')->count();

但这会给我一个错误:

在非对象上调用成员函数 addEagerConstraints()"

如何在关系中接收计数值??

请帮忙!谢谢

【问题讨论】:

    标签: php database laravel orm relational-database


    【解决方案1】:

    @Warren Moore 几乎是正确的,但我刚刚找到了更好的解决方案:

    protected $appends = array('file_count');
    
    public function getFileCountAttribute()
    {
       return $this->files->count()
    }
    

    这将为每个文件对象附加一个file_count 属性

    【讨论】:

    • 这行得通。但是,它似乎不仅附加了 file_count 属性,而且还附加了所有文件。
    【解决方案2】:

    关系方法必须返回Illuminate\Database\Eloquent\Relations\Relation 类型的对象。您的 files() 函数没有问题,但它不是关系,因此不能在您的 projects() 函数中使用。

    问题代码是 with('files'),因为 Laravel 期望从 files() 函数返回一个 Illuminate\Database\Eloquent\Relations\Relation 类型的对象,而是收到一个 int

    您可以手动将此值添加到模型中。尝试将此添加到您的 StoredFile 模型中:

    public function fileCount() {
      return $this->hasMany('File', 'hash', 'user_hash')->count();
    }
    

    更改User 模型:

    public function projects() {
      return $this->hasMany('StoredFile', 'user_id', 'id');
    }
    

    现在使用:

    $projects = $user->projects;
    $project = $project->first();
    $project->fileCount = $project->fileCount();
    var_dump(json_encode($project));
    // {..., "fileCount":"1"}
    

    请记住,每次请求时都会从数据库中查询文件的数量,因此如果您需要返回多个项目,则此方法效率不高。鉴于您返回的是 JSON 响应,但我认为会是这种情况!

    否则,为什么不这样做:

    public function files() {
      return $this->hasMany('File', 'hash', 'user_hash');
    }
    
    public function projects() {
      return $this->hasMany('StoredFile', 'user_id', 'id')->with('files');
    }
    

    现在使用:

    $projects = $user->projects;
    $project = $project->first();
    $project->fileCount = $project->files->count();
    unset($project->files);
    var_dump(json_encode($project));
    // {..., "fileCount":"1"}
    

    类似的东西应该可以吗?

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 2015-04-18
      • 2020-11-06
      • 2019-05-16
      • 2013-07-04
      • 2017-11-23
      • 2020-07-31
      • 2016-02-29
      • 1970-01-01
      相关资源
      最近更新 更多