I'm trying to count all the files within a category, and I have these two relationships:
public function files() {
return $this->hasMany('App\File', 'category_id','category_id');
}
public function fileCount() {
return $this->files()->selectRaw("category_id, count(*) AS count")
->groupBy('category_id');
}
This gives me a collection of items, where the count attribute could be accessed like this:
$my_category = Category::where("category_id", category_id)->with('fileCount')->get();
$file_counter = $my_category->first()->fileCount->first()->count;
Is it possible to directly attach the count attribute to the $my_category variable? Any suggestions will be appreciated.
You can use withCount() method:
$my_category = Category::where("category_id", category_id)
->withCount(['files' => function($q) {
$q->groupBy('category_id');
})
->get();
This will put files_count attribute into results.
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models
Related
I have a total_views attribute added to my Product model like this
public function getTotalViewsAttribute(){
return (int)$this->views()->sum('count');
}
views() is a relationship on Product like this
public function views()
{
return $this->morphMany(View::class, 'viewable');
}
What I would like to do is order my Product by the total_views. Or in other words to order by the sum of the views() relationship.
I have tries to ->orderBy('total_views') on the query but it doesn't seem to work as expected.
Any help will be highly appreciated.
Eloquent getter can only work, when the query has been executed, therefor your current code is not working. I would always use withCount(), on the query;
$products = Product ::withCount(['views'])->get();
The count would be on a property named views_count;.
foreach ($products as $product) {
$product->views_count; // get view count
}
And also possible to order by the column, as it will be present in the SQL returned by the query.
Product ::withCount(['views'])->orderBy('views_count', 'desc')->get();
My user model has a 'prevregistration' attribute
public function prevregistration()
{
return $this->hasMany(Prevregistration::class, 'prevregistration_userid');
}
My prevregistraton model has a 'prev' attribute
public function prev()
{
return $this->hasOne(Prev::class,'prev_id', 'prevregistration_previd');
}
In my controller I show prevregistrations for the current user:
mynextprevs = Auth::user()->prevregistration ;
Now I want to only show prevregistrations from which the connected prev its prev_date in the future, like this:
$mynextprevs = Auth::user()->prevregistration::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::whereDate does not exist.
I also tried like this:
$mynextprevs = Auth::user()->prevregistration->prev::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
Property [prev] does not exist on this collection instance.
Should I/how can I filter the collection? I'm curious why Auth::user()->prevregistration->prev is not working, since that are attributes.
Thanks
You need to use the condition whereHas on your prevregistration
$mynextprevs = Auth::user()->prevregistration()->whereHas('prev',function($prev) {
$prev->whereDate('prev_date', '>=', Carbon::today()->toDateString());
})->get();
Notice we used the relation as a method prevregistration() to access it as a query builder and not as a collection hence the need for the ->get() at the end.
I have found this: Get Specific Columns Using “With()” Function in Laravel Eloquent
but nothing from there did not help.
I have users table, columns: id , name , supplier_id. Table suppliers with columns: id, name.
When I call relation from Model or use eager constraints, relation is empty. When I comment(remove) constraint select(['id']) - results are present, but with all users fields.
$query = Supplier::with(['test_staff_id_only' => function ($query) {
//$query->where('id',8); // works only for testing https://laravel.com/docs/6.x/eloquent-relationships#constraining-eager-loads
// option 1
$query->select(['id']); // not working , no results in // "test_staff_id_only": []
// option 2
//$query->raw('select id from users'); // results with all fields from users table
}])->first();
return $query;
In Supplier model:
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id')
//option 3 - if enabled, no results in this relation
->select(['id']);// also tried: ->selectRaw('users.id as uid from users') and ->select('users.id')
}
How can I select only id from users?
in you relation remove select(['id'])
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id');
}
now in your code:
$query = Supplier::with(['test_staff_id_only:id,supplier_id'])->first();
There's a pretty simple answer actually. Define your relationship as:
public function users(){
return $this->hasMany(User::class, 'supplier_id', 'id');
}
Now, if you call Supplier::with('users')->get(), you'll get a list of all suppliers with their users, which is close, but a bit bloated. To limit the columns returned in the relationship, use the : modifier:
$suppliersWithUserIds = Supplier::with('users:id')->get();
Now, you will have a list of Supplier models, and each $supplier->users value will only contain the ID.
I've been searching for a while and couldn't find an answer, here's what I have:
1- ShowCategory (id & title)
class ShowCategory extends Model
{
public function shows()
{
return $this->belongsToMany(Show::class, 'category_show');
}
}
2- Show (id, title & active)
class Show extends Model
{
public function categories()
{
return $this->belongsToMany(ShowCategory::class, 'category_show');
}
}
So there's a many to many relationship, what I need is retrieving all ShowCategory elements that has at least one Show related to it, and to filter each ShowCategory->shows by show.active, only return shows that are active
Here's what I'm trying to do:
$categories = ShowCategory::whereHas('shows', function($query) {
$query->where('shows.active', '=', true);
})->get();
It only filters ShowCategory that includes shows and if only one of those shows are active, it returns the category with all shows inside, even if others are not active, I need to filter those who are not active.
What should I do? Thanks in advance
This requires a combination of whereHas() and with(). First, whereHas() will filter the ShowCategory model to those that have an active Show, while the with() clause will limit the results of the relationship to only return active ones:
$categories = ShowCategory::whereHas("shows", function($subQuery) {
$subQuery->where("shows.active", "=", true); // See note
})->with(["shows" => function($subQuery){
$subQuery->where("shows.active", "=", true);
}])->get();'
Note: You should be able to use active instead of shows.active, but depends on if that column is on multiple tables.
Using this query, you will get a Collection of ShowCategory models, each with their active Show models already loaded and available via ->shows:
foreach($categories AS $category){
dd($category->shows); // List of `active` Shows
}
This is what you need.
$categories = ShowCategory::whereHas('shows', function($query) {
$query->whereActive(true);
})->get();
Try, this can be a possible way to retreive related results.
// This will only return ShowCategory which will have active shows.
/* 1: */ \ShowCategory::has('shows.active')->get();
// So, logically this will only have active shows -__-
$showCategory->shows
Laravel allows to extends foreign relation by using this . notation as a condition for retreival.
Update
You should update the \ShowCategory model as
public function shows(){
return $this->belongsToMany(Show::class, 'category_show')->where('active', true);
}
I have several relationships, one specifically that I would like to use for ordering a list, but I can't seem to find the right way to do it.
Below are my relationships:
public function date(){
return $this->hasOne(agent_billings_dates::class,'id','dateID');
}
public function carrier(){
return $this->hasOne(customer::class,'id','carrierID');
}
As well as two attributes which I have added as appends:
public function getItemCountAttribute(){
return $this->items->count();
}
public function getItemMissingAttribute(){
return $this->itemIssues->count();
}
public function getBatchSumAttribute(){
return $this->items->sum('amount');
These show up all fine when I have the following in my function:
$batches = agent_billings_batches::with(['date','carrier','carrier.carrierDetails'])
->where('status',$request->status)
->get();
But the attributes and the with's fall off when I do this (however the date is sorted appropriately):
$batches = agent_billings_batches::with(['carrier','carrier.carrierDetails'])
->join('agent_billings_dates', 'agent_billings_dates.id', '=', 'agent_billings_batches.dateID')
->orderBy('agent_billings_dates.date','desc')
->where('status',$request->status)
->get();
Am I doing something wrong? I'd appreciate any help anyone could give.
Thanks!
Eloquent does not use Joins when loading relationships. It loads them in a separate query, therefore you cannot order the main result using a relationship at query time, you need to do it after the data is collected:
$batches = agent_billings_batches::with(['date','carrier','carrier.carrierDetails'])
->where('status',$request->status)
->get()
->sortBy(function ($batch) {
return $batch->date->date;
});