Multiple Queries from multiple tables with laravel - php
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.
Related
Trending query Laravel
Right now I have a subquery to get the count of payments for the current month and then getting the 4 products with the highest payment_count. This query works fine but I'm wondering if there's a more simple way to do the same since its getting difficult to read. $latestPayments = DB::table('payments') ->select('product_id', DB::raw('COUNT(*) as payments_count')) ->whereMonth('created_at', Carbon::now()->month) ->groupBy('product_id'); $trendingProducts = DB::table('products') ->joinSub($latestPayments, 'latest_payments', function ($join) { $join->on('products.id', '=', 'latest_payments.product_id'); })->orderBy('payments_count', 'DESC')->take(4)->get();
This did it! $trendingProducts = Product::withCount(['payments' => function($query) { $query->whereMonth('created_at', Carbon::now()->month); }])->orderBy('payments_count', 'DESC')->take(4)->get();
If you are using eloquent query with relational database you can do like this: $latestPaymentWithTrendingProduct = App\Payment::with(['products', function($product) { $product->orderBy('payments_count', 'DESC')->take(4); }])->whereMonth('created_at', date('m'))->get()->groupBy('product_id'); This will lessen the code but still do the same thing.
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'));
Laravel 5.4 joining two tables
I'm quite lost here. I am trying to get the list of people who are on the Records table which aren't on the Profiles tables which has the specific course (e.g Psychology) and year (e.g 2011). So far, this is what I came up with and unfortunately it's not working. $check = Record::join('Profiles', function ($join) { $join->on('Records.firstname', '!=', 'Profiles.firstname'); $join->on('Records.lastname', '!=', 'Profiles.lastname'); $join->on('Records.middlename', '!=', 'Profiles.middlename'); }) ->select('Records.*', 'Profiles.*') ->where('Records.year', '2011') ->where('Records.course', 'Psychology') ->get(); dump($check); Is there any way that I can go around about this? I'm new to this. Thanks in advance. Advises and tips on joining tables would be greatly appreciated.
Please try a NOT EXISTS subquery: use Illuminate\Database\Query\Builder; $check = \DB::table('Records') ->whereNotExists(function(Builder $query) { $query->select(\DB::raw(1)) ->from('Profiles') ->whereRaw('Records.firstname = Profiles.firstname') ->whereRaw('Records.middlename = Profiles.middlename') ->whereRaw('Records.lastname = Profiles.lastname'); }) ->select('firstname', 'middlename', 'lastname') ->where('year', 2011) ->where('course', 'Psychology'); ->get();
I would look at doing a left outer join and then selecting the records that have a null profile name. $check = Record::leftJoin('Profiles', function ($join) { $join->on('Records.firstname', '=', 'Profiles.firstname'); $join->on('Records.lastname', '=', 'Profiles.lastname'); $join->on('Records.middlename', '=', 'Profiles.middlename'); }) ->select('Records.*', 'Profiles.*') ->where('Records.year', '2011') ->where('Records.course', 'Psychology') ->whereNull('Profiles.firstname') ->get();
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.
Query building using Kohana Query Builder
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();