How to use condition with query builder - php

I have orders table which contains status, paymode, pay_status column
I want to get order if paymode is cod then pay_status unconfirmed can get
and
if paymode is payu then pay_status only confirmed can get
Here I tried with whereRaw
$orders = Order::whereHas('products', function (Builder $query) use ($seller) {
$query->where('seller_id', $seller->id);
})
->whereRaw('IF (`paymode` = `payu`, `pay_status` = `confirmed`)')
->paginate(25);
but it's not working

you can try like this also for multiple conditions
$orders = Order::whereHas('products',
function (Builder $query) use ($seller) {
$query->where('seller_id', $seller->id);
})->whereRaw('paymode = ? AND pay_status = ?', ['payu','confirmed'])
->orWhereRaw('paymode = ? AND pay_status = ?', ['cod','unconfimed '])
->paginate(25);

Related

How to get Complex relation in a Laravel using eloquent

I have below tables
Users
id
name
Companies
id
user_id
name
Product Categories
id
company_id
name
Products
id
product_category_id
name
Sales
id
product_id
price
quantity
total
Now i want to get all sales for specified user's products. I have tried with below query. But i cannot use where for this. It is not apply this filter. Also i want to filter it by few other fields like users.user_name, products.product_name ... etc
$sales = Sale::with(['product'=>function($q) use ($user_id) {
$q->with(['product_category' => function($q) use ($user_id) {
$q->with(['company'=> function($q) use ($user_id) {
$sUserName = Input::get('sUserName');
$q->with(['user'=> function($q) use ($sUserName,$user_id) {
$q->where('id', $user_id);
}]);
}]);
}]);
}]);
Is it possible to use Eloquent for these situations ? Or should i use join queries ? Please advice me. thanks
you can use laravel eloqunt like this.
$Sales = DB::table('Sales')
->join('Products', 'Sales.product_id', '=', 'Products.id')
->join('ProductCategories', 'ProductCategories.id', '=', 'Products.product_category_id')
->join('companies', 'ProductCategories.company_id', '=', 'companies.id')
->join('Users', 'companies.user_id', '=', 'Users.id')
->select('Sales.*')
->get();
After madalinivascu advise i could be able to resolve my problem as below. Now i can filter it by Ordered User, Product name & dates.
$sUserName = Input::get('sUserName');
$sProductName = Input::get('sProductName');
$sFrom = Input::get('sFrom');
$sTo = Input::get('sTo');
$user_id = \Auth::User()->id;
// Show sales only for his products
$sales = Sale::with('sold_to_user')
->whereHas('sold_to_user', function($q) use ($sUserName) {
if(!empty($sUserName)) $q->where('name','LIKE', "$sUserName%");
})->with('product')
->whereHas('product', function($q) use ($sProductName) {
if(!empty($sProductName)) $q->where('name','LIKE', "$sProductName%");
});
if(\Auth::User()->privilege!='administrator') $sales = $sales->where('user_id','=',$user_id);
$sales = $sales->orderBy('updated_at','desc')->paginate(100);

How to use multiple OR,AND condition in Laravel queries

I need help for query in laravel
My Custom Query: (Return Correct Result)
Select * FROM events WHERE status = 0 AND (type="public" or type = "private")
how to write this query in Laravel.
Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();
But it's returning all public events that status is not 0 as well.
I am using Laravel 5.4
Pass closure into the where():
Event::where('status' , 0)
->where(function($q) {
$q->where('type', 'private')
->orWhere('type', 'public');
})
->get();
https://laravel.com/docs/5.4/queries#parameter-grouping
In your case you can just rewrite the query...
select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");
And with Eloquent:
$events = Event::where('status', 0)
->whereIn('type', ['public', 'private'])
->get();
When you want to have a grouped OR/AND, use a closure:
$events = Event::where('status', 0)
->where(function($query) {
$query->where('type', 'public')
->orWhere('type', 'private');
})->get();
Use this
$event = Event::where('status' , 0);
$event = $event->where("type" , "private")->orWhere('type' , "public")->get();
or this
Event::where('status' , 0)
->where(function($result) {
$result->where("type" , "private")
->orWhere('type' , "public");
})
->get();
Try this. It works for me.
$rand_word=Session::get('rand_word');
$questions =DB::table('questions')
->where('word_id',$rand_word)
->where('lesson_id',$lesson_id)
->whereIn('type', ['sel_voice', 'listening'])
->get();
$filter = [];
$filter[] = "type="public" or type = "private"";
$filter[] = "status = 0";
$event = Event::whereRaw(implode(' AND ',$filter))->get();
You can store all condition in filter array and then apply to query

Laravel 5.2 whereRaw with muliple where conditions

below is my query . i want to get all results If (nic or mobile) and course matches ,
please advice
$conversations = Inquiries::whereRaw("( `course` = $request->input('course'))
AND( `mobile` = $request->input('mobile') OR 'nic', 'LIKE', '%'.$request->input('nic').'%')")
->get();
You need to properly create a query, like this:
$conversations = Inquiries::where('course', '=', $request->input('course'))
->where(function($query) use ($request) {
$query->where('mobile','=', $request->input('mobile'))
->orWhere('nic','LIKE','%'.$request->input('nic').'%');
})
->get();

Select all tables values inside whereExist - Laravel

I have to select few other columns as well instead of just top table columns. I have the code;
$records_all = DB::table('table1')
->whereExists(function($query) use ($date) {
$query->select(DB::raw(1))
->from('table2')
->whereRaw('table2.table1_id = table1.table1_id')
->whereNotExists(function($query) use ($date) {
$query->select(DB::raw(1))
->from('table3')
->whereRaw('table2.table2_id = table3.table2_id')
->whereRaw("DATE(table3.date)='" . $date . "'");
});
})
->orderBy('url')
->get();
This gives me records for table1 when required. but how to get anything from table2 or table3 ?
I am using laravel 4.2
Thanks for any help.
change DB::raw(1) to specific column you need and separate column by comma
$records_all = DB::table(DB::raw('table1, table2, table3'))
->select('table1.*','table2.table2_id','table3.table3_id')
->whereExists(function($query) use ($date) {
$query->from('table2')
->whereRaw('table2.table1_id = table1.table1_id')
->whereNotExists(function($query) use ($date) {
$query->from('table3')
->whereRaw('table2.table2_id = table3.table2_id')
->whereRaw("DATE(table3.date)='" . $date . "'");
});
})
->orderBy('url')
->get();
to get print last executed query just after above statement
$queries = DB::getQueryLog();
$last_query = end($queries);
print_r($last_query);exit;

Laravel orWhereHas not working as expected

I'm trying to use the orWhereHas method in Laravel with nested relations, but I am not getting the result I expect. Am I misunderstanding how to use this method?
My relationships are set up as follows:
Product
-> hasOne uniqueItem
-> hasMany fulfillmentCenterUniqueItems
-> hasMany skus
-> hasOne uniqueItem
-> hasMany fulfillmentCenterUniqueItems
I'm trying to test out the whereHas and orWhereHas methods by retrieving products from the database that contain uniqueItems that have a uniqueItemFulfillmentCenter with id = 7089 OR products that contain a sku, that contains a uniqueItem, that has a uniqueItemFulfillmentCenter with id = 7412.
Based on the data in my database, the result of this query should be two products. Product IDs 105 and 239.
Here's the Eloquent code I'm using:
$product = Spire_models\Product
::whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
})
->orWhereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
})
->get()->toArray();
For some reason, this is only returning product ID 105, instead of 105 and 239. The generated sql from this function is:
select * from `products` where `products`.`deleted_at` is null and (select count(*) from `unique_items` where `products`.`unique_item_id` = `unique_items`.`id` and (select count(*) from `fulfillment_center_unique_items` where `fulfillment_center_unique_items`.`unique_item_id` = `unique_items`.`id` and `id` = 7089 and `fulfillment_center_unique_items`.`deleted_at` is null) >= 1 and `unique_items`.`deleted_at` is null) >= 1 and (select count(*) from `skus` where `skus`.`product_id` = `products`.`id` and (select count(*) from `unique_items` where `skus`.`unique_item_id` = `unique_items`.`id` or (select count(*) from `fulfillment_center_unique_items` where `fulfillment_center_unique_items`.`unique_item_id` = `unique_items`.`id` and `id` = 7412 and `fulfillment_center_unique_items`.`deleted_at` is null) >= 1 and `unique_items`.`deleted_at` is null) >= 1 and `skus`.`deleted_at` is null) >= 1
Is this sql being generated incorrectly, or am I misusing the orWhereHas method? To me it does not look like the OR statement is being placed correctly in the sql.
If I remove the orWhereHas method, things works as expected. For example, if I run this:
$product = Spire_models\Product
::whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
})
->get()->toArray();
I correctly get back product ID 105. If I run this:
$product = Spire_models\Product
::whereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
})
->get()->toArray();
I correctly get back product ID 239. So the individual pieces of the query work correctly, but it seems when I try to combine these with an orWhereHas, I get unexpected results. Any idea why?
EDIT
As per the comments, it looks like this is a bug. I was able to temporarily work around it by rewriting the code to use where and orWhere. Here's the temporary solution:
$product = Spire_models\Product
::where(function ($query)
{
$query->whereHas('uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7089);
});
})
->orWhere(function ($query)
{
$query->whereHas('skus.uniqueItem.fulfillmentCenterUniqueItems', function ($query)
{
$query->where('id', 7412);
});
})
->get()->toArray();
It was a bug and is fixed by now with this PR https://github.com/laravel/framework/pull/8171
It's been OK since version 5.0.21

Categories