Laravel eloquent model where datetime less than or equal - laravel-5

I am having an expire_datetime field in Test model and it has many relationship with Candidate model. I want to get all the tests which exipre_datetime is less than or equeal to now datetime. I am doing like this but I am getting all the records, date comparirion is not functioning.
Test Model:
public function testcandidates()
{
return $this->hasMany(Candidate::class,'test_id','id');
}
TestController:
$tests = Test::with([
'testcandidates' => function ($query) {
$query->where('result', '=', 'assigned');
}
])
->where('expire_datetime', '<=', Carbon::now('UTC'))
->get();

Try to get string from carbon: Carbon::now('UTC')->toDateTimeString()
$tests = Test::with(
['testcandidates' => function ($query) {
$query->where('result', '=', 'assigned');
}])
->where('expire_datetime', '<=', Carbon::now('UTC')->toDateTimeString())
->get();

Related

Laravel model get all results, but if model has relation then check for certain condition

Assume I have book models and borrow models. They are one-to-many relationships. I want to get a collection of all the books but return the result if the book is borrowed within the current week. But if it's not, then don't display. I've been trying whereHas(), but I think it didn't suit what I'm looking for.
$displayed_books = Books::orderBy('updated_at', 'DESC')
->ifHasborrow('borrow', function ($query) {
$query->where('start_date', '>=', currentweek())
->where('end_date', "<=", currentweek());
})
$displayedBooks = Books::orderBy('updated_at', 'DESC')
->where(function ($query) {
$query->whereHas('borrow', function($query) {
$now = Carbon::now();
$query->where([
['start_date', '>=', $now->startOfWeek()],
['end_date', '<=', $now->endOfWeek()]
]);
$query->orWhereDoesntHave('borrow');
})
})->get();

Why is the model loading while whereHas is false?

I have this query:
$result = PortingItem::whereHas('porting', function ($query) {
$query->whereIn('status', [
Porting::STATUS_REQUESTED,
Porting::STATUS_ACCEPTED,
Porting::STATUS_DELAYED,
]);
})->where(function ($query) use ($numbers) {
$query->whereBetween('phone_number_start', [$numbers[0], $numbers[1]])
->orWhereBetween('phone_number_end', [$numbers[0], $numbers[1]]);
})->orWhere([
['phone_number_start', '<=', $numbers[0]],
['phone_number_end', '>=', $numbers[1]],
])->get();
The PortingItem model still returns the query result while the porting relation is empty. I don't understand why this happens.
This is my Porting model relation
public function items()
{
return $this->hasMany(PortingItem::class);
}
This is my PortingItem model relation:
public function porting()
{
return $this->belongsTo(Porting::class);
}
You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.
$result = PortingItem::whereHas('porting', function ($query) {
$query->whereIn('status', [
Porting::STATUS_REQUESTED,
Porting::STATUS_ACCEPTED,
Porting::STATUS_DELAYED,
]);
})->where(function ($query) use ($numbers) {
$query->where(function ($query) use ($numbers) {
$query->whereBetween('phone_number_start', [$numbers[0], $numbers[1]])
->orWhereBetween('phone_number_end', [$numbers[0], $numbers[1]]);
})->orWhere(function ($query) use ($numbers) {
$query->where('phone_number_start', '<=', $numbers[0])
->where('phone_number_end', '>=', $numbers[1]);
});
})->get();
https://laravel.com/docs/8.x/queries#logical-grouping

Querying a database relationship with carbon in laravel

I'm trying to select the picture with the most likes from a category the previous day. However, my query returns a null result. My pictures are related to the likes through a has many polymorphic relationship.
Here is my query:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereDate('created_at', Carbon::yesterday());
})
->orderBy('likes_count', 'desc')
->with('user')
->first();
Here is my likeable relationship:
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
Thank you for your help.
Try this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereBetween('created_at', [Carbon\Carbon::yesterday()->startOfDay(), Carbon\Carbon::yesterday()->endOfDay()]);
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
or this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->where('created_at', '>=', Carbon::yeserday()->startOfDay())
->where('created_at', '<=', Carbon::yesterday()->endOfDay());
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
Both of them should return picture with the highest likes the previous day (yesterday)
This query selects the picture with most likes without taking into consideration the other days' likes:
$foodOfTheDay = Picture::where('picture_type', 'food')->withCount(['likes' => function($query) {
$query->whereBetween('created_at', [Carbon::yesterday()-
>startOfDay(), Carbon::yesterday()->endOfDay()]);
}])
->orderBy('likes_count', 'asc')
->with('user')
->first();

How to implement relationship in where condition Laravel's eloquent?

I have two tables:
Students
Results
The two tables have one to may relationship.
Student model:
public function results()
{
return $this->hasMany('App\Result');
}
Result model:
public function student()
{
return $this->belongsTo('App\Student');
}
In the students table I have a field called average_score.
How can I execute the following query, this is not working it says "Undefined property: Illuminate\Database\Query\Builder::$student":
$data = Result::with('student')->where('score', '>=', function($q){
$average_score = $q->student->average_score;
return $average_score;
})->get();
In order to get the results that are only higher or equal to than the "average_score".
If score and average_score are columns of the same table (student), try this;
$data = Result::with(['student' => function ($query) {
$query->whereColumn('score', '>=', 'average_score');
}])->get();
If score and average_score are columns of the different tables, try this;
$data = Result::with('student')->whereHas('student', function($q) {
$q->whereColumn('students.average_score', '<=', 'results.score');
})->get();
You can use whereHas to find those results:
$data = Result::with('student')->whereHas('student', function($q) {
$q->whereColumn('average_score', '<=', 'Results.score');
})->get();
get value from column Results.average_score then compare to student.score:
Result::with([
'student' => function($query) {
$query->where("score",">=", "Results.average_score"););
}
])

Laravel eloquent order by subquery

I have a problem with ordering by columns in subquery (lastname, firstname).
I already tried this code as suggested by other posts:
->with(['customer' => function ($query) {
$query->orderBy("lastname", "asc")
->orderBy("firstname", "asc");
}])
Here my full code, but it doesn't work.
return Membership::forCompany($companyId)
->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
->where(function ($query) {
$query->where('end_date', '>=', Carbon::now()->toDateString())
->orWhereNull('end_date');
})
->with('federation')
->with(['customer' => function ($query) {
$query->orderBy("lastname", "asc")
->orderBy("firstname", "asc");
}]);
Here the relationships:
In customer model I have:
public function memberships() {
return $this->hasMany('App\Models\Membership');
}
In Membership model I have:
public function customer() {
return $this->belongsTo("App\Models\Customer");
}
Try orderBy() with join() like:
$memberships = \DB::table("memberships")
->where("company_id", $companyId)
->where(function ($query) {
$query->where('end_date', '>=', Carbon::now()->toDateString())
->orWhereNull('end_date');
})
->join("customers", "memberships.customer_id", "customers.id")
->select("customers.*", "memberships.*")
->orderBy("customers.lastname", "asc")
->get();
dd($memberships);
Let me know if you are still having the issue. Note, code not tested! so you may need to verify by yourself once.

Resources