Following is my query
$user = User::with(['session' => function ($query) {
$query->select('id','device_id');
$query->where('api_token', '=', '123456');
}])->get();
session: hasMany relation with User.
I am expecting a user with a session having api_token = 123456. Instead I am getting whole users here. I know I am doing something wrong.
I am referring this doc. In the doc it is saying that we can add constraint to the query. But here $query->where('api_token', '=', '123456'); this where is not working.
You are not filtering the User, you are filtering the result of the eager loading of 'session'. Eager loading does not have any effect on the base result set in anyway.
It sounds like you want to filter User by the 'existence' of a relationship in the database.
User::whereHas('session', function ($q) {
$q->where('api_token', '12345');
})->get(); // ->first();
Get all Users that have a Session where 'api_token' == '12345'.
Laravel 5.5 Docs - Eloquent - Relationships - Querying Relationship Existence
Finally I got it worked.
$sessionSelect = function ($query) {
return $query->select( 'user_id', 'device_id');
};
$detailSelect = function ($query) {
return $query->select('user_id', 'dob', 'gender');
};
$sessionWhere = function ($query) use ($key) {
return $query->where('api_token', $key);
};
$users = User::with(['session' => $sessionSelect,'detail'=>$detailSelect])
->whereHas('session', $sessionWhere)
->first();
Related
I am getting data from multiple tables in relation with each other. But in one of the relation I want to get userAnswers records by where('user_id, $userID). What is correct syntax for it
public function survey_completed_show($userSurvey, $userID)
{
$userSurvey = UserSurvey::with('survey.questions.userAnswers')->find($userSurvey);
return view('surveys.conducted-answers', compact('userSurvey'));
}
I just want to get answers of the selected User, I am currently getting all answers by each user
you can use deep with:
$userSurvey = UserSurvey::with(['survey'=>function($query)use( $userID){
$query->with(['questions'=>function($query)use( $userID){
$query->with(['userAnswers'=>function($query)use( $userID){
$query->where('user_id', $userID);
}]);
}]);
}])->find($userSurvey);
Assuming you only need to filter the relation and not the UserSurvey you might wanna try this
public function survey_completed_show($userSurvey, $userID)
{
$userSurvey = UserSurvey::with(['survey.questions.userAnswers' => function($q) use ($userID){
$q->where('user_id', $userID);
}])->find($userSurvey);
return view('surveys.conducted-answers', compact('userSurvey'));
}
I have created many-to-many relation using belongsToMany function:
class Doctor extends Model
{
...
public function categories()
{
return $this->belongsToMany('App\Category', 'doctors_to_categories', 'doctor_id', 'category_id');
}
...
}
Now I want to create query with many-to-many condition. In SQL in would be:
SELECT *
FROM `doctors`
JOIN `doctors_to_categories`
ON `doctors_to_categories`.`doctor_id` = `doctors`.`id`
WHERE `doctors_to_categories`.`category_id` = 1
I have tried to achieve this like:
$doctors = Doctor::with(['categories' => function($query) {
$query->where('category_id', '=', 1);
}])->get();
Or
$doctors = Doctor::with(['categories' => function($query) {
$query->where('categories.id', '=', 1);
}])->get();
But it is not working. Any ideas how it should be? Thanks for any help.
The with() function does not actually introduce a join in your query, it just loads the relation of all models as a second query. So the with() function couldn't possibly change the original result set.
What you are looking for is whereHas(). This will add a WHERE EXISTS clause to the existing query.
$doctors = Doctor::with('categories')->whereHas('categories', function ($query) {
$query->where('categories.id', 1);
})->get();
Using ->with() doesn't actually limit the results of the Doctor::...->get() query; it simply tells Laravel what to return in the relationships attribute. If you actually want to enforce returning only Doctors that have a category 1 relationship, you need to use whereHas():
$doctors = Doctor::whereHas('categories', function($query) {
$query->where('categories.id', '=', 1);
// `id` or `categories.id` should work, but `categories.id` is less ambigious
})->get();
You can add whereHas condition for this. Try code below:
$doctors = Doctor::with('categories')->whereHas('categories', function($query) {
$query->where('id', 1);
})->get();
I'm currently using this function to gather all of my users with a relationship
$users = users::with(array('statusCurrent' => function($query)
{
$query->where('status.status', 'in');
$query->orderBy('status.date', 'DESC');
}));
$users = $users->get();
This returns both of my users, and if status = 'in' then it returns the relationship aswell, but if status = 'out' it still returns the row, but with status_current = null.
Basically I want to ignore the user completely if the arguments inside the with query builder function are not true.
I have tried $candidates = $candidates->has('statusCurrent')->get(); to try and only get results where the relationship is not null, but it still returns users where the StatusCurrent relationship is null.
How do I do it so that foreach of the users, if whatever arguments I pass into the with(array('statusCurrent' => function(){}) are not true, it is ignored completely?
EDIT
Users Model
public function statusCurrent(){
return $this->hasOne('App\Status', 'user_id', 'id')->orderBy('date', 'desc')->limit(1);
}
The user can have many status', but the StatusCurrent relationship is meant to return their 1 most recent status based on the status.date
You need whereHas to filter out users based on their relationship
$users = users::with(array('statusCurrent' => function($query)
{
$query->orderBy('status.date', 'DESC');
}))
->whereHas('statusCurrent', function ($query) {
$query->where('status', 'in');
})
->get();
See Querying Relationship Existence
I am trying to find a record in User model , if the record doesn't exists in User model, Then find it in UserCompany model with relation name company in User model.
$companyUser = \App\User::whereHas('company', function ($query) use ($request) {
$query->where('company_email', '=', $request->email);
})->where('email', $request->email)->get();
I am getting empty set there, What am i missing.
You can do like this,
$companyUser = \App\User::where('email', $request->email)
->orWhereHas('company', function ($query) use ($request) {
$query->where('company_email', '=', $request->email);
})->get();
In Laravel we can setup relationships like so:
class User {
public function items()
{
return $this->belongsToMany('Item');
}
}
Allowing us to to get all items in a pivot table for a user:
Auth::user()->items();
However what if I want to get the opposite of that. And get all items the user DOES NOT have yet. So NOT in the pivot table.
Is there a simple way to do this?
Looking at the source code of the class Illuminate\Database\Eloquent\Builder, we have two methods in Laravel that does this: whereDoesntHave (opposite of whereHas) and doesntHave (opposite of has)
// SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id AND id = 1) < 1) AND ...
User::whereDoesntHave('Role', function ($query) use($id) {
$query->whereId($id);
})
->get();
this works correctly for me!
For simple "Where not exists relationship", use this:
User::doesntHave('Role')->get();
Sorry, do not understand English. I used the google translator.
For simplicity and symmetry you could create a new method in the User model:
// User model
public function availableItems()
{
$ids = \DB::table('item_user')->where('user_id', '=', $this->id)->lists('user_id');
return \Item::whereNotIn('id', $ids)->get();
}
To use call:
Auth::user()->availableItems();
It's not that simple but usually the most efficient way is to use a subquery.
$items = Item::whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
})
->get();
If this was something I did often I would add it as a scope method to the Item model.
class Item extends Eloquent {
public function scopeWhereNotRelatedToUser($query, $user_id)
{
$query->whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
});
}
}
Then use that later like this.
$items = Item::whereNotRelatedToUser($user_id)->get();
How about left join?
Assuming the tables are users, items and item_user find all items not associated with the user 123:
DB::table('items')->leftJoin(
'item_user', function ($join) {
$join->on('items.id', '=', 'item_user.item_id')
->where('item_user.user_id', '=', 123);
})
->whereNull('item_user.item_id')
->get();
this should work for you
$someuser = Auth::user();
$someusers_items = $someuser->related()->lists('item_id');
$all_items = Item::all()->lists('id');
$someuser_doesnt_have_items = array_diff($all_items, $someusers_items);
Ended up writing a scope for this like so:
public function scopeAvail($query)
{
return $query->join('item_user', 'items.id', '<>', 'item_user.item_id')->where('item_user.user_id', Auth::user()->id);
}
And then call:
Items::avail()->get();
Works for now, but a bit messy. Would like to see something with a keyword like not:
Auth::user()->itemsNot();
Basically Eloquent is running the above query anyway, except with a = instead of a <>.
Maybe you can use:
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
Source: http://laravel.com/docs/4.2/queries#advanced-wheres
This code brings the items that have no relationship with the user.
$items = $this->item->whereDoesntHave('users')->get();