Get max count from laravel eloquent relationship - laravel

I have a model Topic which has hasMany relationship with Game model.
//Topic.php
public function Games() {
return $this->hasMany(Game::class);
}
//Game.php
public function Topic() {
return $this->belongsTo(Topic::class);
}
What I need is getting the Topic which has the max count (also the count value) of Games based on 'created_at' today,this week,this month etc. I tried the following code, but the nested whereBetween query does not work, instead it is showing all the related topic->games created ever
$top_topic_month = Topic::with('games')->get()->sortBy(function($q)
{
return $q->games->whereBetween('created_at',[today()->startOfMonth, today()])->count();
})->first();
$top_topic_month_count = ?

try this
use withCount to generate games_count
$top_topic_month = Topic::withCount('games')->whereHas('games',function($q) use($startMonth){
$q->whereBetween('created_at', [$startMonth, today()]);
})->orderByDesc('games_count')->first();
$top_topic_month_count = $top_topic_month->count()

Related

Get Average from Polymorphic Relation

I am both trying to get the review counts and the average review ratings.
I have tables:
Tables:
id
.....
Chairs:
id
.....
Reviews:
id
rating
reviewable_id
reviewable_type
class Review extends Model {
public function reviewable() {
return $this->morphTo();
}
}
class Tables extends Model {
public function reviews() {
return $this->morphMany('App\Review', 'reviewable');
}
public function avg_rating() {
return $this->reviews()
->selectRaw('avg(rating) as avgRating, review_id')
->groupBy('review_id');
}
}
I've tried:
Table::with(['avg_rating'])->withCount('reviews')->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();
But get "Unknown column 'review_id' in 'field list'" or attempting it with variations of "hasmany" yielded only an empty array or an array with the reviews. Just wonder what the best way to accomplish this is or if I'd have to loop through the reviews and calculate manually or a second raw query
I have this but not sure if it is efficient or best practice within Eloquent:
$tables->each(function ($table) {
$table->review_average = DB::table('reviews')
->select(DB::raw("ROUND( avg(rating), 2) as avg"))
->where("reviewable_id", "=", $table->id)->first()->avg;
});
Apparently, I was using Lumen based on the Laravel 6 framework, so it had been throwing a "method not found" error when I tried "withAvg" before. But after searching for that method, I saw that it required a higher version of Laravel. So, updating to Laravel/Lumen 8 allowed me to use the "withAvg" function.
So now my query builder statement looks like:
Table::with(['avg_rating'])->withCount('reviews')->withAvg("reviews", "rating")->where(function($q) use ($regex_terms, $terms){
$q->where('name', 'REGEXP', $regex_terms);
})->get();

How to order by column in nested level relationship in Laravel and get first order by?

I have two model.finance has many price.i want to get just one price (last record according to time) for every finance.so used function and order by and first of each orderby.but this just works for first finance and the other i get null in the with relation.
public function prices()
{
return $this->hasMany(Price::class, 'finance_id');
}
public function finances()
{
return $this->belongsTo(Finance::class, 'finance_id');
}
$finances = Finance::with(['prices' => function ($query) {
$query->orderBy('created_at', 'desc')->first();
}])->get();
Create new relationship in your Finance model to get latest price:
public function latestPrice()
{
return $this->hasOne(Price::class)->latest();
}
Change your query as below:
$finances = Finance::with('latestPrice')->get();

Laravel oneToMany accessor usage in eloquent and datatables

On my User model I have the following:
public function isOnline()
{
return $this->hasMany('App\Accounting', 'userid')->select('rtype')->latest('ts');
}
The accounting table has activity records and I'd like this to return the latest value for field 'rtype' for a userid when used.
In my controller I am doing the following:
$builder = App\User::query()
->select(...fields I want...)
->with('isOnline')
->ofType($realm);
return $datatables->eloquent($builder)
->addColumn('info', function ($user) {
return $user->isOnline;
}
})
However I don't get the value of 'rtype' for the users in the table and no errors.
It looks like you're not defining your relationship correctly. Your isOnline method creates a HasMany relation but runs the select method and then the latest method on it, which will end up returning a Builder object.
The correct approach is to only return the HasMany object from your method and it will be treated as a relation.
public function accounts()
{
return $this->hasMany('App\Accounting', 'userid');
}
Then if you want an isOnline helper method in your App\User class you can add one like this:
public function isOnline()
{
// This gives you a collection of \App\Accounting objects
$usersAccounts = $this->accounts;
// Do something with the user's accounts, e.g. grab the last "account"
$lastAccount = $usersAccounts->last();
if ($lastAccount) {
// If we found an account, return the rtype column
return $lastAccount->rtype;
}
// Return something else
return false;
}
Then in your controller you can eager load the relationship:
$users = User::with('accounts')->get(['field_one', 'field_two]);
Then you can do whatever you want with each App\User object, such as calling the isOnline method.
Edit
After some further digging, it seems to be the select on your relationship that is causing the problem. I did a similar thing in one of my own projects and found that no results were returned for my relation. Adding latest seemed to work alright though.
So you should remove the select part at very least in your relation definition. When you only want to retrieve certain fields when eager loading your relation you should be able to specify them when using with like this:
// Should bring back Accounting instances ONLY with rtype field present
User::with('accounts:rtype');
This is the case for Laravel 5.5 at least, I am not sure about previous versions. See here for more information, under the heading labelled Eager Loading Specific Columns
Thanks Jonathon
USER MODEL
public function accounting()
{
return $this->hasMany('App\Accounting', 'userid', 'userid');
}
public function isOnline()
{
$rtype = $this->accounting()
->latest('ts')
->limit(1)
->pluck('rtype')
->first();
if ($rtype == 'Alive') {
return true;
}
return false;
}
CONTROLLER
$builder = App\User::with('accounting:rtype')->ofType($filterRealm);
return $datatables->eloquent($builder)
->addColumn('info', function (App\User $user) {
/*
THIS HAS BEEN SUCCINCTLY TRIMMED TO BE AS RELEVANT AS POSSIBLE.
ARRAY IS USED AS OTHER VALUES ARE ADDED, JUST NOT SHOWN HERE
*/
$info[];
if ($user->isOnline()) {
$info[] = 'Online';
} else {
$info[] = 'Offline';
}
return implode(' ', $info);
})->make();

latest() helper function in laravel

I'm building a small application where I'm having many to many relationship between two models something like this:
class Contact extends Model
{
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact', 'company_id', 'contact_id')->withTimestamps();
}
}
Now while retrieving this I want only the latest model through the pivot table or you may say relational table, for this I'm trying to implement:
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->latest()->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
But I'm unable to retrieve the latest table it is showing the same old value or the first value.
Guide me how can I achieve this.
You can try this :
latest() is a function defined in Illuminate\Database\Query\Builder Class.
public function latest($column = 'created_at')
{
return $this->orderBy($column, 'desc');
}
So, It will just orderBy with the column you provide in descending order with the default column will be created_at
OR
public function getData()
{
$allData = Contact::all();
foreach($allData as $data)
{
$getCompany = $data->company()->orderBy('created_at', 'desc')->first();
$data->company = $getCompany;
}
return response()->json(['model' => $allData], 200);
}
So basically idea is if you are finding the relational data from many to many relation like $data->company() in this question and try to sort this with latest it will sort the company table with created_at sorting desc in order to get relational latest data you need to sort through pivot tables i.e.
$getCompany = $data->company()->withPivot('created_at')->orderBy('pivot_cr‌​eated_at', 'desc')->first();
This is how I achieved the latest relational table.
Note: You must have pivot table in your relation, in this answer created_at is the pivot field I'm using.

Laravel Eloquent model with counter

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

Resources