How to convert this query in Laravel? - laravel

How do I convert this query to laravel form?

Somthing along the lines of:
Stocks::where('shop_id', $client_id)
->where(function ($query) use ($client_id, $ware_cd) {
$query->where('ware_id',
DB::raw(
'select ware_id from t_ware where shop_id=' . $client_id . ' and ware_cd=' . $ware_cd
)
);
})
->distinct()
->get();

Related

using whereNotIn and subquery in query builder (Laravel 8)

I would like to make a controller function to search for users by name and display only those name that are not already in a project.
here is the SQL query to display users with name containing 'mmm' who are not already in project id = 2:
SELECT `firstname`
FROM `user_details`
WHERE (
`firstname` LIKE "%mmm%" AND `user_id` NOT IN (
SELECT `member_id` FROM `project_members` WHERE `project_members`.`project_id` = 2)
)
and in the query builder (which doesn't work):
$searchResults = DB::table('user_details')
->select('user_details.user_id', 'user_details.firstname', 'user_details.lastname', 'user_details.nickname', 'user_details.status')
->whereNotIn('user_details.user_id', DB::table('project_members')
->select('member_id')
->where('project_id', '=', $request->project_id)
->get()
->toarray()
)
->where('user_details.firstname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.lastname', 'LIKE', '%'.$request->searchString.'%')
->get();
Do you know where I did wrong? Thank you!
Got it. I just needed ->pluck('member_id') instead of toarray()
And also, where/orWhere must be grouped.
$searchResults = DB::table('user_details')
->select('user_details.user_id', 'user_details.firstname', 'user_details.lastname', 'user_details.nickname', 'user_details.status')
->whereNotIn('user_details.user_id', DB::table('project_members')
->select('member_id')
->where('project_id', '=', $request->project_id)
->get()
->pluck('member_id')
)
->where(function ($query) use ($request) {
$query->where('user_details.firstname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.lastname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.nickname', 'LIKE', '%'.$request->searchString.'%');
})
->get();

How to wrap Eloquent query with parenthesis when we use a conditional clauses in Laravel 5.7

I have a query that should load all the posts with just their english translation.
If the user enter a keyword it return just the english post with a title containing that keyword.
if ($searchKeywords||$searchCategory){
$posts = Post::
select('post_translations.post_id AS id', 'post_translations.title AS title', 'category_id', 'locale')
->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
->where(‘post_translations.locale','=','en')
->when($searchKeywords, function ($query, $searchKeywords) {
return $query->where('post_translations.title', $searchKeywords)->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
})
->when($searchCategory, function ($query, $searchCategory) {
return $query->where('category_id', '=', $searchCategory);
->paginate(20);
}
else
$posts = Post::select('id', 'title', 'category_id')->orderBy('title')->paginate(20);
The generated query is this one:
SELECT `post_translations`.`post_id` AS `id`, `post_translations`.`title` AS `title`, `category_id`
FROM `posts` inner join `post_translations`
ON `posts`.`id` = `post_translations`.`post_id`
WHERE `post_translations`.`locale` = 'en'
AND `post_translations`.`title` = 'About'
OR `post_translations`.`title` like 'About’
LIMIT 20 OFFSET 0
That return me all the 3 posts translations of the post About.
This because of the orWhere.
How can I change the eloquent query in order to generate a query like this?
SELECT `post_translations`.`post_id` AS `id`, `post_translations`.`title` AS `title`, `category_id`
FROM `posts` inner join `post_translations`
ON `posts`.`id` = `post_translations`.`post_id`
WHERE `post_translations`.`locale` = 'en'
AND (`post_translations`.`title` = ‘About' OR `post_translations`.`title` like 'About’ )
LIMIT 20 OFFSET 0
The question is not a duplicate of this one because I have one more level of subquery.
How do you wrap Laravel Eloquent ORM query scopes in parentheses when chaining?
Add both condition inside a where query like this:
if ($searchKeywords) {
$posts = Post::select('post_translations.post_id AS id', 'post_translations.title AS title', 'category_id', 'locale')
->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
->where(‘post_translations.locale','=','en')
->where(function ($query) use ($searchKeywords) {
$query->where('post_translations.title', $searchKeywords)
->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
})
->paginate(20);
}
I have solved with this code:
if ($searchKeywords||$searchCategory){
$posts = Post::
select('post_translations.post_id AS id', 'post_translations.title AS title', 'category_id', 'locale')
->join('post_translations', 'posts.id', '=', 'post_translations.post_id')
->when($searchKeywords, function ($query, $searchKeywords) {
return $query->where('post_translations.locale','=','en')
->where(function ($query) use ($searchKeywords) {
$query->where('post_translations.title', $searchKeywords)->orWhere('post_translations.title', 'like', '%' . $searchKeywords . '%');
});
})
->when($searchCategory, function ($query, $searchCategory) {
return $query->where('post_translations.locale','=','en')
->where(function ($query) use ($searchCategory) {
$query->where('category_id', '=', $searchCategory);
});
})
->paginate(20);
}
else
$posts = Post::select('id', 'title', 'category_id')->orderBy('title')->paginate(20);

Conditional query with WhereBetween in Laravel

I've got the following controller function section for a little search block form:
$manifests = DB::table('carrier_manifests')
->join('customers', 'carrier_manifests.carrierOrigin', '=', 'customers.id')
->select('carrier_manifests.*', 'customers.customer_name')
->where([
['manifestNumber', 'LIKE', '%' . $manifest . '%'],
['originTerminal','LIKE','%' . $terminal . '%'],
['carrierOrigin', $direction[0], $direction[1]],
])
->whereNull('deleted_at')
->orderBy('dateUnloaded', 'DESC')
->whereBetween('dateUnloaded', [$startDate, $endDate])
->limit(100)
->get();
Every part of it works correctly except for one section, the whereBetween, because of a workflow necessity, sometimes the dateUnloaded in the clause is not filled in for every carrier_manifest, so that means if the dateUnloaded field is empty, it will be left out of the search results.
Are there any suggestions for how to include those results missing the dateUnloaded?
You should be able to do a nested where() for the null values or between like:
$manifests = DB::table('carrier_manifests')
->join('customers', 'carrier_manifests.carrierOrigin', '=', 'customers.id')
->select('carrier_manifests.*', 'customers.customer_name')
->where([
['manifestNumber', 'LIKE', '%' . $manifest . '%'],
['originTerminal','LIKE','%' . $terminal . '%'],
['carrierOrigin', $direction[0], $direction[1]],
])
->whereNull('deleted_at')
->orderBy('dateUnloaded', 'DESC')
->where(function($query) use ($startDate, $endDate) {
return $query->whereBetween('dateUnloaded', [$startDate, $endDate])
->orWhereNull('dateUnloaded');
})
->limit(100)
->get();
So from what I have understood is that dateUnloaded may or may not be provided to the query.
In such a case you can use the when method of laravel
Example taken from laravel docs
https://laravel.com/docs/5.6/queries
$users = DB::table('users')
->when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();
Here you can see that if $role is present then only the query will be executed otherwise not.
Please Try This...
$manifests = DB::table('carrier_manifests')
->join('customers', 'carrier_manifests.carrierOrigin', '=', 'customers.id')
->select('carrier_manifests.*', 'customers.customer_name')
->where([
['manifestNumber', 'LIKE', '%' . $manifest . '%'],
['originTerminal','LIKE','%' . $terminal . '%'],
['carrierOrigin', $direction[0], $direction[1]],
])
->whereNull('deleted_at')
->orderBy('dateUnloaded', 'DESC')
->where(function($q) use ($startDate,$endDate){
if($endDate !="" && $startDate !=""){
$q->whereBetween('dateUnloaded', [$startDate, $endDate]);
}
return $q;
})
->limit(100)
->get();

Laravel eloquent search on fields of related model

I have an eloquent models as,
User : users(id, username, password, email, status)
Profile : profiles(id, user_id, first_name, last_name, gender, dob)
In the controller logic, I am eagerly loading the Profile model.
I can do this,
$user = User::with('Profile')->get();
or
$user = User::with('Profile')->where('status', '1')->get();
but how to do something like,
$user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get();
That's where whereHas comes in handy:
$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){
$q->where('gender', 'Male');
})->get();
Basically it adds the condition that the user needs to have a profile with gender = Male
If you want to search multiple columns in relation model.
$searchText = 'test text';
Product::with('owner')->where(function($query) use ($searchText)
{
$query->where('product_name', 'LIKE', '%' . $searchText . '%');
$columns = ['product_code', 'place_location', 'remark'];
foreach ($columns as $column ) {
$query->orWhere($column, 'LIKE', '%' . $searchText . '%');
}
$query->orWhereHas('owner', function($q) use ($searchText) {
$q->where(function($q) use ($searchText) {
$q->where('name', 'LIKE', '%' . $searchText . '%');
$q->orWhere('company_name', 'LIKE', '%' . $searchText . '%');
});
});
});
Let's say you've multiple relations
and you want to search records based on multiple relational columns value
User::with('associate')
->where('name', 'like', '%' . $input . '%')
->orWhere(function ($query) use ($input) {
$query->whereHas('associate', function ($q) use ($input) {
$q->where('first_name', 'like', '%' . $input . '%');
});
})
->orWhere(function ($query) use ($input) {
$query->with('roles')->whereHas('roles', function ($q) use ($input) {
$q->where('display_name', 'like', '%' . $input . '%');
});
})
->get();
Suppose, Your search input field name is q.
function name(Request $request){
$query = User::select();
if($request->q && $request->q !=''){
// if you search
$keyword = $request->q;
$query = User::with('Profile')->whereHas('Profile', function($q) use
($keyword){
$q->where('gender', 'like', "%{$keyword}%" );
});
}
$query->latest('id')->paginate();
}

Laravel 4: A where and whereIn inside a whereHas using Eloquent

Laravel 4 - advanced Where
I'm trying to retrieve Posts that have a $keyword like a certain Companion and besides that I want to retrieve the Posts the have a linking title or content as the $keyword.
But when I try to use a where or whereIn inside a whereHas the query doesn't take these into account. When the state is 0 (not visible) or not inside the category 1 the Post item should not get selected.
$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id');
The code block below has to do two things:
Search for Post items with a title or content like the $keyword
and search for Post items that have Companions like the $keyword
code:
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id)
->where('state', '=', 1)
->whereIn('category_id', array(1));
})
->whereIn('category_id', array(1))
->orwhere('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' )
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();
The code above retrieves data succesfully except for the where and whereIn parts inside the whereHas.
Who can help me out?
wrap your orWhere clauses in (..)
you don't need where and whereIn in the whereHas closure, since it queries companions table
you don't need whereIn for category_id, unless you want to pass multiple ids there
.
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id);
})
->whereIn('category_id', array(1)) // why not where(..) ?
->where(function ($q) use ($keyword) {
$q->where('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' );
})
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();
Thanks to Jarek Tkaczyk.
His answer was almost correct. All I had to do was wrap the where inside a orWhere. Now I get the Posts that has a Companion like the $keyword and I get the Posts that has the $keyword inside the content or title.
$results = Post::whereHas('companions', function($query) use($companion_id)
{
$query->whereIn('companions.id', $companion_id)
->where('state', '=', '1');
})
->orWhere( function($q) use ( $keyword ) {
$q->where('title', 'LIKE', '%' . $keyword . '%' )
->orWhere('content', 'LIKE', '%' . $keyword . '%' );
})
->whereIn('category_id', array(1, 3))
->where('state', '=', '1')
->orderBy('menu_order', 'desc')
->get();

Resources