Following is my MySQL query
SELECT id
FROM member_measurement_records
WHERE date in (SELECT MAX(date) from member_measurement_records GROUP BY type)
Which I want to write using laravel eloquent.
Can you please help me. As I am new to this.
Well, there are several ways to do it.
Using DB facade
$data = DB::table('member_measurement_records')->where('date', DB::raw("(select max(`date`) from member_measurement_records GROUP BY type)"))->get();
Using eloquent and raw query
$data = MemberMeasurementRecords::whereRaw('date = (select max(`date`) from member_measurement_records GROUP BY type)')->get();
Using Eloquent and DB facade
$data = MemberMeasurementRecords::find(DB::table('member_measurement_records')->max('date')->groupBy('type'));
Haven't tested it, but you can try it:
(It is assumend your corresponding model is called MemberMeasurementRecords)
MemberMeasurementRecords::whereIn('date', function ($query) {
$query->max('date')->orderBy('type');
})->get('id');
Related
I'm trying to make a complex query using Laravel Eloquent. I know how to do it using raw SQL query, but I don't have any idea how to do it using Eloquent.
Here is my SQL query, and it works perfectly:
select *
from students
where exists(select *
from (select student_movements.id AS sm_id, student_movements.direction, student_movements.deleted_at
from student_movements
inner join student_student_movements
on student_movements.id = student_student_movements.student_movement_id
where students.id = student_student_movements.student_id
and student_movements.deleted_at is null
order by student_movements.id desc
limit 1) as last_sm
where last_sm.direction = 1 AND last_sm.date >= 5-5-2022
);
My models have many-to-many relation using student_student_movements table:
Student
public function studentMovements(): BelongsToMany
{
return $this->belongsToMany(
StudentMovement::class,
'student_student_movements',
);
}
StudentMovement
public function students(): BelongsToMany
{
return $this->belongsToMany(
Student::class,
'student_student_movements'
);
}
My goal is to get all Students, who have the last Movement where direction = 1 and the date of the last Movement >= $someDate.
So, my question is: how to translate the SQL query to Eloquent? I saw many similar questions, but they are not helping me.
Thanks for any advice.
Use the whereHas method, then fine tune the sub query inside the closure to your needs.
You can use the whereHas and orWhereHas methods to define
additional query constraints on your has queries.
There is an example like that in laravel documentation
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->get();
// Retrieve posts with at least ten comments containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
}, '>=', 10)->get();
check the documentation here
I'm having trouble to write query in laravel eloquent ORM.
I have a proyect table, where you can assign users, in a many to many relationship
In the view to asign users, I have a selector, but I want to show only the users not already assigned to the proyect and checking also that the user belongs to the company that created the proyect (user.company_id=proyect_id)
In a normal query should me something like this, having $company_id and $proyect_id from the controller.
select * from users u left join proyect_user pu on u.id=pu.user_id and
pu.proyect_id = $proyect_id where u.company_id=$company_i and
proyect_id is null;
The query works, but I would like to use Eloquent. ¿Any idea how to do it?
It depends on how you declared the relationship in the User model. But I would do something like this:
$users = User::whereHas('company', function ($query) use ($companyId) {
$query->where('id', $companyId)
})->whereDoesntHave('proyects', function ($query) use ($proyectId) {
$query->where('id', $proyectId);
})->get();
How do I convert this MySQL query to Laravel Eloquent Query:
SELECT * FROM service_package WHERE price IN ('110010', 'Test 02', '11009')
You can use the whereIn() like:
Using DB::table()
$data = \DB::table("service_package")
->whereIn("price", ['110010', 'Test 02', '11009'])
->get();
Using Eloquent
$data = App\ServicePackage::whereIn("price", ['110010', 'Test 02', '11009'])
->get();
Here, make sure you have created model ServicePackage for the table service_package.
Can I use Eloquents active record to create this query or do I need to use the query builder?
SELECT
*
FROM
chat
inner join chat_member as member1
on member1.chat_id = chat.chat_id
inner join chat_member as member2
on member2.chat_id = chat.chat_id
WHERE
member1.chat_member_id = $member1ID
and member2.chat_member_id = $member2ID
WhereHas() function is to filter from relationship queries.
Make sure you have Chat and Member Models.
And Chat Model has members() relationship.
Then you can achieve your mysql query as follow.
Chat::whereHas('members', function ($query) {
$query->where('chat_member_id', $member1ID);
})
->whereHas('members', function($query) {
$query->where('chat_member_id', $member2ID);
})
->get();
Update, I fixed a syntax issue
I have two Models User and Owner with many to many relationship
I want to fetch only those users who don't have owner
how can I get using eloquent
i tried
$query = User::whereHas('userOwners', function ( $subquery ){
$subquery->whereNull('owner_id');
})->get();
but not working.
Eloquent has a way to query an absent relationships, it should work like this in your case:
$query = User::doesntHave('userOwners')->get();
User::with('userOwners')
->whereHas('userOwners', function ($query) {
$query->wherehas('owner_id');
})
->where('user_status', 1)->get();
use second where if you want to filter on user
use first where if you want to filter on Owner
I think you should just change your query like:
$query = User::whereHas('userOwners')->get();
Hope this work for you!!!