Related
I'm trying to dynamically select columns based on if-else conditional logic.
$records = DB::table('dmf_result_set_assign as rsa')
->select(
'pmu.s_image_url', 'pmu.r_image_url', 'pmu.r_image_url_main', 'pmu.product_sku',
'pmu.product_name', 'pmu.product_id', 'pmu.ai_result',
'pmu.confidence_score', 'pmu.request_id',
if($distinct_only_flag) {
DB::raw('DISTINCT pmu.hash_id'),
'pmu.run_date_id',
'pmu.s_product_url',
'pmu.r_product_url',
'pmu.s_price',
'pmu.s_mpn',
'pmu.s_upc',
'pmu.s_asin',
'pmu.s_gtin',
'pmu.s_variant_info',
'pmu.s_brand',
'pmu.s_category',
'pmu.s_description'
} else {
'pmu.hash_id',
'fr.filter_name',
'rsa.human_verdict', 'rsa.assigned_to',
DB::raw('CONCAT(usr.first_name, " ", usr.last_name) as cloud_user')
}
)
->join('dmf_product_match_unmatches as pmu', DB::raw('BINARY `pmu`.`hash_id`'), '=', 'rsa.hash_id')
->join('dmf_filter_rules as fr', 'fr.id', '=', 'rsa.filter_rule_id')
->leftjoin('dmf_user_tokens as tkn', 'tkn.id', 'rsa.assigned_to')
->leftjoin('users as usr', 'usr.id', '=', 'tkn.user_id')
->get();
I get this error:
(1/2) FatalThrowableError
Parse error: syntax error, unexpected 'if' (T_IF)
But when I try this, it's working:
$records = DB::table('dmf_result_set_assign as rsa')
->select(
'pmu.s_image_url', 'pmu.r_image_url', 'pmu.r_image_url_main', 'pmu.product_sku',
'pmu.product_name', 'pmu.product_id', 'pmu.hash_id', 'pmu.ai_result',
'pmu.confidence_score', 'pmu.request_id', 'fr.filter_name',
'rsa.human_verdict', 'rsa.assigned_to', DB::raw('CONCAT(usr.first_name, " ", usr.last_name) as cloud_user'),
if($distinct_only_flag) {
DB::raw('DISTINCT(pmu.hash_id)')
} else {
'pmu.hash_id'
}
)
->join('dmf_product_match_unmatches as pmu', DB::raw('BINARY `pmu`.`hash_id`'), '=', 'rsa.hash_id')
->join('dmf_filter_rules as fr', 'fr.id', '=', 'rsa.filter_rule_id')
->leftjoin('dmf_user_tokens as tkn', 'tkn.id', 'rsa.assigned_to')
->leftjoin('users as usr', 'usr.id', '=', 'tkn.user_id')
->get();
I couldn't figure out the issue. Both looks similar and yet one works and other doesn't.
Is there any other to achieve this?
you could do it using addSelect method:
$records = DB::table('dmf_result_set_assign as rsa')
->select(
'pmu.s_image_url', 'pmu.r_image_url', 'pmu.r_image_url_main', 'pmu.product_sku',
'pmu.product_name', 'pmu.product_id', 'pmu.ai_result',
'pmu.confidence_score', 'pmu.request_id',
)
->join('dmf_product_match_unmatches as pmu', DB::raw('BINARY `pmu`.`hash_id`'), '=', 'rsa.hash_id')
->join('dmf_filter_rules as fr', 'fr.id', '=', 'rsa.filter_rule_id')
->leftjoin('dmf_user_tokens as tkn', 'tkn.id', 'rsa.assigned_to')
->leftjoin('users as usr', 'usr.id', '=', 'tkn.user_id');
if ($distinct_only_flag) {
$records = $records->addSelect(DB::raw('DISTINCT pmu.hash_id'),
'pmu.run_date_id',
'pmu.s_product_url',
'pmu.r_product_url',
'pmu.s_price',
'pmu.s_mpn',
'pmu.s_upc',
'pmu.s_asin',
'pmu.s_gtin',
'pmu.s_variant_info',
'pmu.s_brand',
'pmu.s_category',
'pmu.s_description');
} else {
$records = $records->addSelect('pmu.hash_id',
'fr.filter_name',
'rsa.human_verdict', 'rsa.assigned_to',
DB::raw('CONCAT(usr.first_name, " ", usr.last_name) as cloud_user'))
}
$records = $records->get();
I use this query and i get a error :
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where(['sender_id' => $user_id, "%$description%", 'LIKE','description'])
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}
and this is the error that I get :
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where
clause' (SQL: select * from transcation_historique where
(sender_id = 32 and 0 = %salaire% and 1 = LIKE and 2 =
description) or receiver_id = 32)"
and this what really i want to run:
select * from `transcation_historique` where (`sender_id` = 32 and `description` = %salaire%) or `receiver_id` = 32)
Try this,
$description_query = Transcationhistorique::where(
function($query) use ($user_id, $description){
return $query->where('sender_id', $user_id)
->where('description', 'like', '%' . $description .'%');
}
)
->orWhere('receiver_id', $user_id)
->get();
It seems like your where query is not structured correctly.
You should use the following structure if you want to use operators other than "="
Source
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
My suggestion is:
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where([
['sender_id', '=', $user_id],
['description', 'LIKE', "%{$description}%"]
])
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}
Try this one:
Transcationhistorique::where('receiver_id', '=', $user_id)
->orWhere(function ($query) use ($user_id, $description) {
$query->where('sender_id', '=', $user_id)->where('description', 'LIKE', "%".$description."%");
})->get();
You can use multiple where method as and.
Can you try following codes?
$description = $request->get('description');
if (!empty($description)){
$description_query = Transcationhistorique::where('sender_id', $user_id)
->where("description", 'LIKE','%' . $description . '%')
->orWhere('receiver_id', $user_id)->get();
}else{
$description_query = "" ;
}
I am trying to write an API with the image stored in Database as blob I am getting no response as JSON but getting a result as standard object or array.code
{
$menu_cat_data = [];
$main_categories = DB::table('categories')->select('categories.id as menu_category_id', 'categories.name as menu_category_name',
'categories.image as menu_category_image')
->join('products', 'categories.id', '=', 'products.CATEGORY')
->where('categories.SITEGUID', '=', $id)
->distinct()
->get();
if (count($main_categories) > 0) {
$cnt = 0;
$menu_cat_data = [];
foreach ($main_categories as $main_categorys) {
$main_categorys['menu_category_image'];
$menu_cat_data['menu'][$main_categorys- >menu_category_id] = (array) $main_categorys;
$products = DB::table('products')->select('products.id as menu_item_id', 'products.name as menu_item_name',
'products.PRICESELL as rate', 'products.image as menu_product_image')
->where('products.SITEGUID', '=', $id)
->where('products.category', '=', $main_categorys->menu_category_id)
->join('categories', 'products.category', '=', 'categories.id')
->distinct()
->get();
if (count($products) > 0) {
foreach ($products as $product) {
$menu_cat_data['menu'][$main_categorys->menu_category_id]['items'][$product->menu_item_id] = (array) $product;
}
}
}
}
$response = json_encode($menu_cat_data);
print_r($response);
}
I have situation in laravel 5.1 with eloquent. That is very hard for me at this time to get the solution.
I have 7 tables in database which are not related to each other, but I want to get results with joining them all and with where clause.
My Tables relations are:
lifegroups -> Campuses -> locations -> address
and
lifegroups -> grouptype -> groupuser -> user // this is confusing little bit
and
lifegroups -> schedule -> recurrance
Notice the lifegroup table is associated with multiple other tables.
My Existing Query is:
$campusGroups = DB::table('campuses')
->Join('lifegroups','campuses.f1_id', '=', 'lifegroups.campusId')
->Join('locations', 'locations.group_id', '=', 'lifegroups.f1Id')
->Join('addresses', 'addresses.location_id', '=', 'locations.id')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct() //'users.first_name', 'users.last_name',
->select('lifegroups.*', 'campuses.name AS campusname', 'addresses.address', 'addresses.address2', 'addresses.city', 'addresses.province');
$groupLeaders = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct()
->select('lifegroups.id', 'users.first_name', 'users.last_name');
$groupRecurrences = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('schedules', 'schedules.event_id', '=', 'lifegroups.eventid')
->Join('recurrences', 'recurrences.schedule_id', '=', 'schedules.id')
->distinct()
->select('recurrences.occurOnFriday', 'recurrences.occurOnSaturday', 'recurrences.occurOnMonday', 'recurrences.occurOnSunday', 'recurrences.occurOnThursday', 'recurrences.occurOnTuesday', 'recurrences.occurOnWednesday', 'recurrences.recurrenceFrequency', 'recurrences.recurrenceFrequencyMonthly', 'recurrences.recurrenceFrequencyWeekly', 'schedules.start_date', 'schedules.recurrence', 'lifegroups.id AS groupId');
if (Session::has('campus')){
$campusId = Session::get('campus');
$searchObj = $campusGroups->where('campuses.id', intval($campusId));
$groupLeaders = $groupLeaders->where('campuses.id', intval($campusId));
$groupRecurrences = $groupRecurrences->where('campuses.id', intval($campusId));
$searchArray['campusId'] = $campusId;
}
if (Session::has('gender')){
$gender = Session::get('gender');
$searchObj = $campusGroups->where('lifegroups.gender', $gender);
$groupLeaders = $groupLeaders->where('lifegroups.gender', $gender);
$groupRecurrences = $groupRecurrences->where('lifegroups.gender', $gender);
$searchArray['gender'] = $gender;
} else {
$searchArray['gender'] = 'N/A';
}
if (Session::has('marital_status')){
$marital_status = Session::get('marital_status');
$searchObj = $campusGroups->where('lifegroups.marital_status', $marital_status);
$groupLeaders = $groupLeaders->where('lifegroups.marital_status', $marital_status);
$groupRecurrences = $groupRecurrences->where('lifegroups.marital_status', $marital_status);
$searchArray['marital_status'] = $marital_status;
} else {
$searchArray['marital_status'] = 'N/A';
}
if (Session::has('age')){
$age = Session::get('age');
$searchObj = $campusGroups->where('lifegroups.startAgeRange', $age);
$groupLeaders = $groupLeaders->where('lifegroups.startAgeRange', $age);
$groupRecurrences = $groupRecurrences->where('lifegroups.startAgeRange', $age);
$searchArray['age'] = $age;
} else {
$searchArray['age'] = 'N/A';
}
if (Session::has('keyword')){
$keyword = Session::get('keyword');
$searchObj = $campusGroups->where('lifegroups.name', 'Like', '%'. $keyword . '%');
//->orWhere('lifegroups.description', 'Like', '%'.$keyword.'%')
//->orWhere('users.first_name', 'Like', '%'.$keyword.'%');
$groupLeaders = $groupLeaders->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$groupRecurrences = $groupRecurrences->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$searchArray['keyword'] = $keyword;
} else {
$searchArray['keyword'] = 'N/A';
}
$campusGroupsTemp = $campusGroups->get();
$campusGroups = [];
$recurrenceGroups = [];
$groupLeaders = $groupLeaders->get();
$groupRecurrences = $groupRecurrences->get();
So this is a very long process and I can't add further search filters. Do you guys have any better idea how to do it with Laravel Eloquent, like
Lifegroups::with(['campuses', 'locations', 'addresses', 'grouptype', 'groupuser', 'users', 'schedules', 'recurrences'])
->where(['lifegroups.name', '=' 'name_value'],['lifegroups.description','like', '%like_valie%'], ['user.first_name', 'like', 'first_name_value'])
->get()->toArray();
If you are confused like me then only let me know how to do below mentioned thing with above type of tables scenario.
This becomes very easy with Eloquent assuming you have your models setup correctly. Just use dot notation to handle the nesting.
$data = Lifegroups::with([
'campuses.locations.address',
['grouptype.groupuser.user', function($q) use ($first_name) {
// Handle the constraints on the users table here.
$q->where('name', 'like', $first_name)
}],
'schedule.recurrance'
])
// Handle any constraints on the Lifegroups table here
->where('name', '=', 'name_value')
->where('description','like', '%like_valie%')
->get();
If you need to add more constraints for different tables, just add another parameter to the array we passed into the with function going as deep as you need to with the nexting and passing in a function with it where you will set the constraints like I did the users table.
In Laravel 4 I have built a search form. Where a person can submit either
email address
From - To date
Ref number
They can only search using one of the above options; As they have to select from a drop down on which they would like to search with. The final code I used to get this working is as follows:
if(Input::get('from') && Input::get('to')){
$records = Applications::where('created_at', '>=', Input::get('from'))
->where('created_at', '<', date('Y-m-d', strtotime(Input::get('to'). ' + 1 days')))
->lists('id');
}elseif(Input::get('email') || Input::get('ref')){
$records = Applications::where('Application_number', '=', Input::get('ref'))
->where('email', '=', Input::get('email'), 'OR')
->lists('id');
}else{
$records = Applications::all()->lists('id');
}
The works for my requirements, but I'm not really happy this is the best solution.
I also tried to use either of the solutions in this thread Laravel 4 eloquent WHERE with OR AND OR?
$result = User::where('created_at', 'LIKE', '%' . $search . '%')
->where('updated_at', 'LIKE', '%' . $search . '%', 'OR')
->where('user_first_name', 'LIKE', '%' . $search . '%', 'AND')
->where('user_any_field', 'LIKE', '%' . $search . '%')->get();
OR
Model::where(function ($query) {
$query->where('a', '=', 1)
->orWhere('b', '=', 1);
})->where(function ($query) {
$query->where('c', '=', 1)
->orWhere('d', '=', 1);
});
But all I kept getting was value can't be null, when searching on from and to; email and ref worked fine.
You can try this:
$input = Input::all();
Model::where(function($query) use ($input) {
if (isset($input['something'])) {
$query->where('some_field_1', '=', $input['something']);
}
if (isset($input['something_else'])) {
$query->where('some_field_2', '=', $input['something_else']);
}
})->get();
I think this is the cleanest way. Of course, you should put the if statements to be of your need.