Query building using Kohana Query Builder - php

If I got this:
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->execute()->as_array();
For normal, dsiplaying all orders date_created. Now I can filter by user, doing this ?user_id=112
This will make me having this:
if(isset($get['user_id']))
{
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->where('user_id', '=', $get['user_id'])
->execute()->as_array();
}else{
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->execute()->as_array();
}
Although this is no problem for me have this, but this get to be real much ugly code when I have 4 params to filter out from(4 where statements) e.g ?user_id=112&quantity=2&...
Can I somehow make a inline if/action statement, which would grab all user_ids if there's nothing in $get['user_id'] ?
So I can end up having only this:
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->where('user_id', '=', (isset($get['user_id']) ? $get['user_id'] : 'GRAB ALL!'))
->execute()->as_array();
or is there another, even better way to do this?
Tried looking in Kohana docs if there's some ->if()->where()->exitif().. (just some imagination of how it could work)

You can modify Query object before executing:
$query = DB::select()->from(...);
if (isset($get['user_id'])) {
$query->where('user_id', '=', intval($get['user_id']));
}
if (isset($get['quantity'])) {
$query->where('quantity', '=', floatval($get['quantity']));
}
$result = $query->execute()->as_array();

Related

Multiple Queries from multiple tables with laravel

I have 12 tables i want to query from the database based on the user search options.
This is a visual schema diagram of the table
selected tables to query visual schema diagram
The is a UI of the select options the user will select to search the database.
UI of query fields
This is the controller i have tried but always have failures.
$center = Input::get("center");
$course = Input::get("course");
$parentInfo = Input::get("parent-info");
$feedingList = Input::get("feeding-list");
$kitCollectionList = Input::get("kit-colection-list");
$paymentStatus = Input::get("payment-status");
$verifiedPayment = Input::get("verified-payments");
$attendanceList = Input::get("attendance-list");
$laptopRentalList = Input::get("laptop-rental-list");
$pinList = Input::get("pins-list");
$siblings = Input::get("siblings");
$gender = Input::get("gender");
$birthday = Input::get("birthdays");
$schoolList = Input::get("school-list");
$schoolLocation = Input::get("school-location");
$studentAge = Input::get("student-age");
$studentClass = Input::get("student-class");
$stateOfOrigin = Input::get("state-of-origin");
$chequeList = Input::get("cheque-list");
$results = DB::table('enrollments')
->join('students', 'enrollments.id', '=', 'students.enrollment_id')
->join('parents', 'enrollments.id', '=', 'parents.enrollment_id')
// ->join('student_pickups', 'enrollments.id', '=', 'student_pickups.enrollment_id')
->join('pins', 'enrollments.id', '=', 'pins.enrollment_id')
->join('student_proxies', 'enrollments.id', '=', 'student_proxies.enrollment_id')
->join('student_courses', 'enrollments.id', '=', 'student_courses.enrollment_id')
->join('student_feedings', 'enrollments.id', '=', 'student_feedings.enrollment_id')
->join('student_laptop_rentals', 'enrollments.id', '=', 'student_laptop_rentals.enrollment_id')
->join('student_expos', 'enrollments.id', '=', 'student_expos.enrollment_id')
->join('payments', 'enrollments.id', '=', 'payments.enrollment_id')
->join('payment_methods', 'enrollments.id', '=', 'payment_methods.enrollment_id')
->join('student_camp_materials', 'enrollments.id', '=', 'student_camp_materials.enrollment_id')
->join('attendances', 'enrollments.id', '=', 'attendances.enrollment_id')
->select('students.center',
'students.student_name',
'students.student_dob',
'students.student_sex',
'students.student_email',
'students.student_phone',
'students.student_home_address',
'students.student_city',
'students.student_school_name',
'students.student_school_city',
'students.student_school_state',
'students.student_state_of_origin',
'students.student_school_address',
'students.student_school_class',
'students.created_at',
'parents.parent_title',
'parents.parent_name',
'parents.relationship',
'parents.parent_email',
'parents.parent_phone',
'parents.parent_home_address',
'parents.parent_work_address',
'parents.parent_office_address',
'parents.created_at',
/*'student_pickups.child_self_pickup',
'student_pickups.drop_off_by_center4tech',
'student_pickups.parent_or_guardian_pick_up',
'student_pickups.proxy_pick_up',
'student_pickups.created_at',*/
'pins.pin_owner_name',
'pins.user_type',
'pins.status',
'pins.sign_in_pin',
'pins.sign_out_pin',
'pins.pick_up_pin',
'pins.drop_off_pin',
'pins.created_at',
'student_proxies.proxy_title',
'student_proxies.proxy_name',
'student_proxies.proxy_gender',
'student_proxies.proxy_phone',
'student_proxies.proxy_relationship',
'student_proxies.created_at',
'student_courses.course_name',
'student_courses.course_type',
'student_courses.course_price',
'student_courses.center',
'student_courses.computer_usage_proficiency',
'student_courses.created_at',
'student_feedings.feeding_pack_label',
'student_feedings.feeding_price',
'student_feedings.feeding_start_date',
'student_feedings.feeding_end_date',
'student_feedings.feeding_expire_notification_sms',
'student_feedings.feeding_expire_notification_email',
'student_feedings.feeding_expire_notification_parent_reminder',
'student_feedings.created_at',
'student_laptop_rentals.laptop_rental_label',
'student_laptop_rentals.laptop_rental_price',
'student_laptop_rentals.laptop_rental_start_date',
'student_laptop_rentals.laptop_rental_end_date',
'student_laptop_rentals.laptop_rental_expire_notification_sms',
'student_laptop_rentals.laptop_rental_expire_notification_email',
'student_laptop_rentals.laptop_rental_expire_notification_parent_reminder',
'student_laptop_rentals.is_rented',
'student_laptop_rentals.is_returned',
'student_laptop_rentals.created_at',
'student_expos.expo_fees',
'student_expos.expo_price',
'student_expos.created_at',
'payments.payment_type',
'payments.invoice_number',
'payments.item_description',
'payments.quantity',
'payments.rate',
'payments.discount',
'payments.total',
'payments.transaction_date',
'payments.verified',
'payments.invoice_sent',
'payments.invoice_sent_by_sms',
'payments.invoice_sent_by_email',
'payments.invoice_sent_date',
'payments.created_at',
'payment_methods.payment_option',
'payment_methods.payment_amount',
'payment_methods.cash_payment_confirmation',
'payment_methods.cash_transaction_timestamp',
'payment_methods.bank_pos_provider',
'payment_methods.bank_pos_transaction_date',
'payment_methods.bank_pos_transaction_time',
'payment_methods.bank_pos_stan',
'payment_methods.bank_pos_rrn',
'payment_methods.bank_pos_ref_no',
'payment_methods.bank_online_sender_account_name',
'payment_methods.bank_online_sender_account_number',
'payment_methods.bank_online_sender_bank',
'payment_methods.bank_online_transaction_date',
'payment_methods.bank_online_miu_research_bank_acc_paid_into',
'payment_methods.bank_online_payment_channel',
'payment_methods.cheque_name',
'payment_methods.cheque_date_to_pay_in',
'payment_methods.cheque_to_be_paid_in_now',
'payment_methods.cheque_is_post_dated',
'payment_methods.cheque_notification_reminder',
'payment_methods.bank_teller_depositor_name',
'payment_methods.bank_teller_transaction_date',
'payment_methods.bank_teller_miu_research_bank_acc_paid_into',
'payment_methods.is_splited_by_cash',
'payment_methods.split_pay_cash_amount',
'payment_methods.is_splited_by_pos',
'payment_methods.split_pay_pos_amount',
'payment_methods.is_splited_by_bank_transfer_online',
'payment_methods.split_pay_bank_transfer_pc_mobile_amount',
'payment_methods.is_splited_by_teller',
'payment_methods.split_pay_deposit_teller_amount',
'payment_methods.is_splited_by_cheque',
'payment_methods.split_pay_cheque_amount',
'payment_methods.is_parted_by_cash',
'payment_methods.is_parted_by_pos',
'payment_methods.is_parted_by_bank_transfer',
'payment_methods.is_parted_by_teller',
'payment_methods.is_parted_by_cheque',
'payment_methods.advance_payment_amount',
'payment_methods.balance_payment_outstanding',
'payment_methods.balance_payment_due_date',
'payment_methods.balance_payment_status',
'payment_methods.pdf_generated',
'payment_methods.receipt_sent',
'payment_methods.receipt_sent_by_sms',
'payment_methods.receipt_sent_by_email',
'payment_methods.receipt_sent_by_pdf',
'payment_methods.receipt_sent_date',
'payment_methods.status',
'payment_methods.created_at',
'student_camp_materials.course_material_given',
'student_camp_materials.electronic_kit_given',
'student_camp_materials.enrollment_completed',
'student_camp_materials.enrollment_not_completed',
'student_camp_materials.created_at',
'attendances.present',
'attendances.absent',
'attendances.sign_in',
'attendances.sign_out',
'attendances.operation',
'attendances.extra',
'attendances.created_at',
)
// ->orWhere('students.center','LIKE','%'.$center.'%')
->orWhere('students.center',$center)
->orWhere('student_courses.course_name',$course)
->orWhere('parents.parent_phone')
->orWhere('parents.parent_email')
->orWhere('parents.parent_office_address')
->orWhere('student_courses.course_name',$course)
->get();
/*if ( isset($center) ) {
$results = Student::where("center",$center)->get();
}
if ( isset($course) ) {
$results = Studentcourse::where("course_name",$course)->get();
}*/
return $results;
That's certainly a long query and I'm sure there is some optimisation to be made - both code and query.
You need to be a little more detailed on what kind of errors you are getting and how we can help, example expected results etc. However, here's a few things I've quickly spotted -
That controller is never going to succeed, the query is flawed.
Most of those variables seem to be going unused. You'd be better off calling them directly from the request and saving a few lines of code.
Some of your where's don't even have a condition - that'll cause a failure.
->orWhere('parents.parent_phone')
->orWhere('parents.parent_email')
->orWhere('parents.parent_office_address')
Probably worth grouping your queries a little more. E.g.
->where(function ($builder) {
$builder
->where('students.center', request()->center)
->orWhere('student_courses.course_name', $course = request()->course)
->orWhere('student_courses.course_name', $course);
})
->get();
Overall I'd really recommend reviewing all of your code and tidying it up where possible.

How to fix whereNotExists and where query builder laravel

I try to combine whereNotExists and where, if you use it simultaneously it will and if you try one of them you can
$query = DB::table('tabel_produk')->where('kode_customer',$cust)->whereNotExists(function($query){
$query->select(DB::raw(1))->from('tabel_detail_realisasi')->whereRaw('tabel_detail_realisasi.barcode = tabel_produk.barcode');
})->distinct()->orderBy('barcode','asc') ->get();
Pleae help me with this
I don't have your DB schema so I've tried something similar with a local DB I have and it seems to be working fine. See my example below. Could you please replace my query with yours and see what's output by the query logger?
DB::flushQueryLog();
DB::enableQueryLog();
$results = DB::table('product_templates')
//Non deleted products
->where('deleted', '=', '0')
//
->whereNotExists(function ($query) {
//Where the category is not 'General'
$query
->select(DB::raw(1))
->from('product_categories')
->whereRaw('product_categories.id = product_templates.category_id')
->where('product_categories.name', 'General');
})
->distinct()
->orderBy('name', 'asc')->get();
DB::disableQueryLog();
$queryLog = DB::getQueryLog();
logger("Query results", compact('results', 'queryLog'));

where() not working in codeigniter database

I wrote this code for search in my table search for a string in posts where show = 1.
but when i run this code where('show',1) not affected and rows where having show = 0 returned from database, what this problem?
public function json_search($str)
{
$out['Threadt'] = $this->db
->select('id')
->from('posts')
->like('title',$str)
->or_like('story',$str)
->or_like('description',$str)
->or_like('full-story',$str)
->where('date <',time())
->where('show',1)
->get()
->result_array();
}
you should try this, this should work:
function json_search($str)
{
$where = "( story like '%".$str."%' OR title like '%".$str."%' OR description like '%".$str."%' OR full-story like '%".$str."%' )";
$out['Threadt'] = $this->db
->select('id')
->from('posts')
/*->like('title',$str)
->or_like('story',$str)
->or_like('description',$str)
->or_like('full-story',$str)*/
->where( $where, false, false )
->where('date <',time())
->where('show',1)
->get()
->result_array();
}
See the commented part above, when you're using it like this, you are appending OR clauses and this interferes with the show clause.

trying to Join 2 table query in Fluent laravel 4

Im trying to Joing 2 table in Fluent trough my Model i run the query on mysql client and give me the return i want.
this is the standard query
select `songlist`.*, `queuelist`.* from `songlist` inner join `queuelist` on `songlist`.`id` = `queuelist`.`songID` where `queuelist`.`songID` = songlist.ID and `songlist`.`songtype` = 'S' and `songlist`.`artist` <> "" order by `queuelist`.`sortID` ASC limit 4
it does return the data im looking for.
now on my model using fluent.
i did like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->join('queuelist', 'songlist.id', '=', 'queuelist.songID')
->select('songlist.*','queuelist.*')
->where('queuelist.songID', '=', 'songlist.ID')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}
and my controller to test if i get the data look like this
public function getComingUp()
{
$getcomingUp = Radio::comingUp();
foreach ($getcomingUp as $cup)
{
echo $cup->title;
}
// return View::make('comingup', compact('comingup'));
}
as you can see the foreach is no returning any data there is nothing wrong with the query because laravel give me no error at all. but i cant just get the foreach to display the data im looking for.
i try with $cup->songlist.title;
and it dont work ether.
Thanks any help will be appretiated. againg sorry for my English.
You can do something like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->select('songlist.*','queuelist.*')
->join('queuelist', 'queuelist.songID', '=', 'songlist.id')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}

laravel using query builder without chaining

I have a query builder that works:
$article = Page::where('slug', '=', $slug)
->where('hide', '=', $hidden)
->first();
But I want to only add the second where statement if hidden is equal to 1. I've tried the code below which shows the logic of what I'm trying to do, but it doesn't work.
$article = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$article->where('hide', '=', 1);
}
$article->first();
I'm using Laravel 4, but I think the question still stands with Laravel 3.
Yeah there's a little "gotcha" with Eloquent and the query builder. Try the code below ;)
$query = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$query = $query->where('hide', '=', 1);
}
$article = $query->first();
Note the assigning of $query within the conditional. This is becuase the first where (statically called) returns a different object to the query object within the conditional. One way to get around this, I believe due to a recent commit, is like so:
$query = Page::where('slug', '=', $slug)->query();
This will return the query object and you can do what you want as per normal (Instead of re-assigning $query).
Hope that helps.

Categories