Eloquent Query, possible Join - mysql

I have three models: driver, designation and dpsObject, with the following replationships:
driver->hasMany(dpsObject)
driver->belongsTo(Designation)
designation->hasMany(Driver)
dpsObject->belongsTo(Driver)
I'm trying to write a query to return a list of dpsObject records that correspond to the values of three user inputs, which are: a date range(From and To) holding the values of an EntryDate field in the dpsObject and a Designation input, holding the value of a Designation_name field in the Designation object.
Currently this is my Query:
$dps = dpsObject::where([['entryDate', '>=', $from],
['entryDate', '<=', $to]]);
$from and $to hold the request values gotten from the form user's submit.
I need to complete the query to capture the Designation name of a driver that that has dpsObject records. The challenge is that the designation_name field does not exist on the dpsObject model but only on the driver and designation models. This is how I want to maintain the database model. I think I need to be using a join or something similar, but I'm not sure how to go about it.
What is the best way to write such a query?
Kind regards

You can use nested whereHas():
$dpsObjects = dpsObject::whereBetween('entryDate', [$from, $to])
->whereHas('driver', function ($q) use($designationName) {
$q->whereHas('designation', function ($q) use($designationName) {
$q->where('designation_name', $designationName);
});
})
->get();
Here, designation and driver are belongsTo() relationships.

Related

Query builder laravel with and select

I want to show "cars.name" in result.
I need to use "cars.name" value to order later
$this->model
->select("pieces.*", "cars.name")
->where('cars_id', $carId)
->with('cars')
->has('cars', '>=', 1);
How can I do that?
You can try to do it this way by passing a closure function in with():
$this->model
->select("pieces.*")
->where('cars_id', $carId)
->with('cars'=> function ($query) {
$query->select('id','name');
}])
->has('cars', '>=', 1);
It will only select id and username from other table.
Remember that the primary key (id in this case) needs to be the first param in the $query->select() to actually retrieve the necessary results.
the first you have built is just a query, then it needs to be retrieved on the server, use get() and you will see error message. Need more info about the relation between pieces and cars to help. Try it -
$this->model::whereHas('cars',function(builder $query)use($cardId){
$query->where('cars_id', $carId);})->has('cars', '>=', 1)->with('cars')->get();
then obtain cars name via denamic property of a relation

How to return the data of another model instance model by using joins in laravel?

I want to return the data of Charge instance instead of User , for that i am trying to use joins ,can you please help me to acheive this thing
$id=Charge::whereNotNull('created_by')->get('created_by')->toArray();
foreach($id as $name){
$id[] = $name['created_by'];
}
return $v=User::whereIn('id',$id)->where('username',$request->data)->get();
}
for this i am trying to use left join , relationship available between created_by and id (I am trying to convert above queries into single query)
$v=Charge::whereNotNull('created_by')->leftJoin('User',function($join){
$join->on('Charge.created_by','=','User.id');
})->get();

Filter With() in Query Scope

Controller
$r = \App\User::whereIn('id', $user_ids)->withPosts($category_id)->get();
User model
public function scopeWithPosts($query, $category_id)
{
return $query->with('posts')->where('category_id', $category_id);
}
I have been at this for too many hours now.
I am trying to use with() along with an query scope to add an extra filter to the relationship.
However it gives me the error " category_id not existing in users table"? What am I missing?
Laravel 6
The problem you are experiencing is that you are expecting the with('posts') function to return a query that is relative to the Posts ORM model. It won't, it will still return a reference to the original query. What you will find is that the with function returns $this, so you'll always get the original query.
What you are attempting is a SQL query to find the User, followed by another SQL query to get all the Post records of that user, with those posts filtered by category. So
SELECT * FROM Users WHERE id=?;
SELECT * FROM Posts WHERE user_id = ? AND category_id = ?
To do that in the Eloquent relationship, you need to subquery, like so:
return $query->with(['posts' => function ($q) use ($category_id) {
$q->where('category_id', $category_id);
}]);
Please comment if you need further info and I'll edit my answer.

convert query from mysql to php laravel?

My query is the following:
select employe.id, employe.nam, users.name, users.name_user
from employe
left join users
on users.name = employe.id
it is a query to two tables: employe, users.
How can I pass it to my controller? Am I new to laravel..
I assume the user to employee is a One to One relation.
Did you setup the relation in both models?
If so you can do the following in your controller:
$employees = Employee::with('user')->all();
This will load all employees and the related user.
Question is the users.name a foreign key on the employee.id?
Thats a bit strange, i recommend using id's on both models (autoIncrement).
Laravel use a MVC pattern, a good practice is use a Model for your employe table
I recomend you to use an Eloquen Model, so, your query will look like this:
Employe::select('employe.id', 'employe.nam', 'users.name', 'users.name_user')
->leftJoin('users', 'users.name', 'employes.id')
->get();
You can easily maintain this kind of query with Eloquent relationships.
Add this method on your employee model
public function user(){
return $this->hasOne('App\User','name','id');
}
Add this method on your user model
public function Employee(){
return $this->belongsTo('App\Employee','id','name');
}
Add line on your controller
$employees = Employee::with('user')->all();

Laravel multiple column eloquent search query

i am very new in Laravel,currently working with Laravel4.I am trying to add a multiple column search functionality in my project.I can do single column eloquent search query,But honestly i have no idea how to do multiple column eloquent search query in laravel.I have two drop down menu
1.Locatiom
2.blood group.
i want to search an user having certain blood group against certain location.That is, user will select a location and blood group from those two drop down menu at a time and hit the search button.
In my database,i have two column, one contains the location and another contains the blood group of a certain user. Now,what should be the eloquent query for such a search?
Simply chain where for each field you need to search through:
// AND
$results = SomeModel::where('location', $location)->where('blood_group', $bloodGroup)->get();
// OR
$results = SomeModel::where('location', $location)->orWhere('blood_group', $bloodGroup)->get();
You can make it easier to work with thanks to the scopes:
// SomeModel class
public function scopeSearchLocation($query, $location)
{
if ($location) $query->where('location', $location);
}
public function scopeSearchBloodGroup($query, $bloodGroup)
{
if ($bloodGroup) $query->where('blood_group', $bloodGroup);
}
// then
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
Just a sensible example, adjust it to your needs.
This is a great way but I think there is an error somewhere as laravel would not allow you to access a non-static function so instead of using
SomeModel::searchBloodGroup($bloodGroup)->searchLocation($location)->get();
you could simply use
SomeModel::BloodGroup($bloodGroup)->Location($location)->get();
take note of the searchBloodGroup has been changed to BloodGroup, that's how you will use it for all others also.
$errors = $connection->table('test_sessions_table')
->where('user_id', $user->id)
->where('status_question', 'false')->count('status_question');
in this method your code takes the following form
SQL code
select count(`status_question`) as aggregate from `test_sessions_table` where `user_id` = ? and `status_question` = ?
orWhere your code will look like this
$errors = $connection->table('test_sessions_table')
->where('user_id', $user->id)
->orWhere('status_question', 'false')->count('status_question');
SQL code
select count(`status_question`) as aggregate from `test_sessions_table` where `user_id` = ? or `status_question` = ?
Personally, I recommend using two ‘where’