How to do this query in Laravel Eloquent?
SELECT * FROM `ftm_users`, `ftm_students`, `ftm_user_verification` WHERE `ftm_users`.`user_group` = 3 AND `ftm_user_verification`.`verification_status` = 1 AND `ftm_users`.`uid` = `ftm_students`.`uid` AND `ftm_users`.`uid` = `ftm_user_verification`.`uid`
I already set the relationship in Model and I have tried with this
$userStudent = User::where('user_group', '=', 3)->with(array('userVerification' => function($query) {
$query->where('verification_status', '=', 1);
}, 'student', 'studentParents'))->simplePaginate(20);
but the query is using separated select statement to get data from different table.
Thanks.
Assuming that you defined the relationships between ftm_users and ftm_user_verification, you can use the whereHas method to filter related models
$userStudent = User::where('user_group', '=', 3)->whereHas('userVerification', function ($query) {
$query->where('verification_status', '=', 1);
})->get();
Check Querying Relationship Existence in the docs
Related
SELECT
posts.id,
(select count(*) from post_likes where post_id = 13 and user_id = 12) as post_like
FROM
posts
LIMIT 5
How to write this query in Laravel query builder?
If your ORM models are defined (and you have both Post and PostLike models), create a relationship in your Post.php model (if not already), like:
public function likes(){
return $this->hasMany(PostLike::class);
}
Then if you only need the count, try something like:
$userId = 12;
$postList = Post::query()
->whereId(13)
->withCount(['likes', 'likes AS post_like' => function ($query) use($userId) {
$query->where('user_id', '=', $userId);
}])
->limit(5)
->get();
// Then do something with result.
foreach ($postList as $post) {
$count = $post['post_like'];
}
Note that above we use post_like alias, and limit to user_id, just to much OP requirements; Else we could simply set likes_count to the number of relations, like:
->withCount('likes')
But you could use relationship for subquery with the whereHas(...) eloquent method, like:
Post::query()->whereHas('likes', function($query){
$query->where(...your statements for sub query go there);
}, '>', 4)->limit(5)->get(); //Select where more than 4 relation found with given parameters
For more see: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
hello everyone I am new in Laravel development and I am wondering how to create subquery between two tables, for example, I want to execute this query :
SELECT * FROM `contracts`
WHERE `trainer_id` = '1' OR id IN (
SELECT `contract_id` FROM `trainees`
WHERE `user_id` = '1'
)
I test it in and it works fine as I want, I want to know how to write it in Laravel eloquent
Assuming that your Model is named Contract you can use the following syntax to achieve what you want:
Contracts::where('trainer_id', '1')
->orWhere(function ($subquery) {
$subquery->whereIn('id', function ($query) {
$query->select('contract_id')
->from('trainees')
->where('user_id', '1');
})
})->get();
I have an Order table with some relationships (Status, User) using their IDs to create it (status_id, user_id)
I need to get a collection of Order models using and Eloquent ORM but I need to filter by their status name (which is in Status table only) and user name (which is in User table only)
When I use 'join' in my query builder. The relationships aren't hydrating, like in this case:
$emprestimo = DB::table('emprestimos')
->join('status', 'status_id', '=', 'status.id')
->where('status.nome', 'Solicitado')
->where('emprestimos.dono_id', Auth::user()->id)
->get();
How can I filter using joins and also hydrate my collection of models?
you can try something like this
see if that works
$emprestimo = DB::table('emprestimos')
->join('status', function ($join) {
$join->on('emprestimos.status_id', '=', 'status.id')
->where('status.nome', 'Solicitado')
})
->where('emprestimos.dono_id', Auth::user()->id)
->get();
I have three tables as below:
users
id|name|username|password
roles
id|name
users_roles
id|user_id|role_id
These tables communicate via belongsToMany.
I would like to find a way to select all data in “users” table except ones that their user value of "role_id" is 5 in table “users_roles”.
How can I do it?
You should use whereDoesntHave() to select models that don't have a related model meeting certain criteria:
$users = User::whereDoesntHave('roles', function($q){
$q->where('role_id', 5);
})->get();
Use Laravel's Query Builder:
<?php
$users = DB::table('users')
->leftJoin('users_roles', 'user.id', '=', 'users_roles.user_id')
->where('users_roles.role_id', '!=', 5)
->get();
http://laravel.com/docs/4.2/queries
Or using Eloquent directly:
<?php
$users = User::whereHas('users_roles', function($q)
{
$q->where('role_id', '!=', 5);
})->get();
http://laravel.com/docs/4.2/eloquent#querying-relations
<?php
$users = User::whereHas('roles', function($query) {
$query->where('id', '<>', 5);
})
->orHas('roles','<', 1)
->get();
I think the correct answer is:
User::whereHas('roles', function ($query) {
$query->whereId(5)
}, '=', 0)->get();
This code should send a query that checks if the role with id=5 is related to the user or not.
Edit
While I think this should work but the #lukasgeiter answer is preferable.
In the end both methods use the has() to count the related models by using a subquery in the db query where clause but when you use the whereDoesntHave() it specifies the operator < and the count 1 itself.
You can var_dump(DB::getQueryLog()) in App::after()'s callback to see the actual query.
I have 2 tables: users and articles. To fetch all columns from the articles table and only user_name column from the users table, I use this code:
$articles = Article::join('users', 'articles.user_id', '=', 'users.user_id')
->get(array('articles.*', 'users.user_name'));
and it works fine, but when I use paginate() method like this:
$articles = Article::join('users', 'articles.user_id', '=', 'users.user_id')
->paginate(10);
it fetches all columns from both tables, which I don't want. My question is: How can I select columns that will be returned in the result if I use paginate() method in Laravel framework?
The select function does this.
$articles = Article::join('users', 'articles.user_id', '=', users.user_id')
->select('articles.*', 'users.user_name')
->paginate(10);