You can't use
return $this->hasMany('File', 'hash', 'user_hash')->count();
as a relationship. Do you want to return another attribute with the project object which contains the number of files attached to that project?
If so you could do something like below in the projects model:
protected $appends = array('file_count');
public function getFileCountAttribute()
{
return $this->files->count()
}
This should include a 'file_count' attribute within the json with the count of how many files are attached to each project.
DanielOReilly said:
You can't use
return $this->hasMany('File', 'hash', 'user_hash')->count();
as a relationship. Do you want to return another attribute with the project object which contains the number of files attached to that project?
If so you could do something like below in the projects model:
protected $appends = array('file_count'); public function getFileCountAttribute() { return $this->files->count() }
This should include a 'file_count' attribute within the json with the count of how many files are attached to each project.
Wow, this works perfectly for me, but one question: can I only return the file_count without files?
You can return the list of files for a project by doing the following.
$projects = Project::with('files')->where('id', $projectId)->first();
This should return a project object with all attached file objects and the file_count attribute.
DanielOReilly said:
You can return the list of files for a project by doing the following.
$projects = Project::with('files')->where('id', $projectId)->first();
This should return a project object with all attached file objects and the file_count attribute.
No, the json response is now:
{"project_name":"test","user_hash":"64650458b6Fhgd68ca57308222","file_count":1,"files":[{"id":1,"name":"example.pdf"}]}
I want file_count only
{"project_name":"test","user_hash":"64650458b6Fhgd68ca57308222","file_count":1}
Then use the getFileCountAttribute() as described above.
#Add this code in your Model.
protected $hidden = ['files'];
Note: files
refers to your relationship's method name.
nasaorc said:
DanielOReilly said:
You can return the list of files for a project by doing the following.
$projects = Project::with('files')->where('id', $projectId)->first();
This should return a project object with all attached file objects and the file_count attribute.
No, the json response is now:
{"project_name":"test","user_hash":"64650458b6Fhgd68ca57308222","file_count":1,"files":[{"id":1,"name":"example.pdf"}]}
I want file_count only
{"project_name":"test","user_hash":"64650458b6Fhgd68ca57308222","file_count":1}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community