Appending attributes based on scope #473
-
Hi, i'm looking into using package in my project and have a question about appending attributes. Let's say i have class Post extends Model {
public function comments()
{
return $this->morphToMany(Comment::class, 'commentable');
}
public function scopeWithCommentsStatistics(Builder $query)
{
$query->/** Some complex query, which counts additional columns **/
}
public function getCommentsStatisticsAttribute()
{
return [
// additional columns from withCommentsStatistics() scope
];
}
} I can get posts list from class PostController extends Controller
{
public function index()
{
$posts = QueryBuilder::for(Post::class)
->allowedFilters([
AllowedFilter::scope('comments_statistics', 'withCommentsStatistics'),
])
->allowedAppends(['comments_statistics'])
->get();
return PostResourceCollection::make($deals);
}
} With following request So the question is there any way to get my comments_statistics attribute with only It could be done applying withCommentsStatistics() scope to all queries, like global scope, but i don't feel like having complex part of query in all queries that works with Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi! I'm not sure we can easily achieve something like this using just appended attributes in this package. The query builder actually only builds queries, allowing appended attributes to be added using this package might've been a mistake 😅 Probably not the answer you were looking for but I'd suggest using Laravel's API resources to achieve this: https://laravel.com/docs/master/eloquent-resources. Using a resource you can conditionally add a couple of statistics fields whenever the fields are loaded in the query. This will probably cleanup your code quite a bit as well. Good luck! |
Beta Was this translation helpful? Give feedback.
Hi! I'm not sure we can easily achieve something like this using just appended attributes in this package. The query builder actually only builds queries, allowing appended attributes to be added using this package might've been a mistake 😅
Probably not the answer you were looking for but I'd suggest using Laravel's API resources to achieve this: https://laravel.com/docs/master/eloquent-resources. Using a resource you can conditionally add a couple of statistics fields whenever the fields are loaded in the query. This will probably cleanup your code quite a bit as well.
Good luck!