CI pagination syntax for getting results - codeigniter

Assume that the config is done and it is intialized, then time for the results to be paginated.
On this line of code.
$data['records'] = $this->db->get('tablename', $config['per_page'], $this->uri->segment(3));
Is there anyway of changing the above line of code. Since I have 3 tables with ERD relationship. So in my 3rd table consists lots of rows that are connected to the other 2 tables. I want to make a model function where i will manually query the results. How am i supposed to write it?
$data['records'] = $this->load->model('manual_querying'), $config['per_page'], $this->uri->segment(3);
Im not sure if its correct, i am still unable to test it if its correct since im not done with my pagination yet.

In model, write a function
public function get_records($per_page,$page)
{
$this->db->select("*");
$this->db->from("table1 as t1");
$this->db->join("table2 as t2","t1.id = t2.t1_id");
$this->db->join("table3 as t3","t1.id = t3.t1_id");
$this->db->limit($per_page,$page);
$res = $this->db->get();
return $res;
}
In controller,
$this->load->model('your_model');
$data['records'] = $this->your_model->get_records($config['per_page'], $this->uri->segment(3));

Related

Unserialize cart data not working Laravel

I'm save my cart products as unserialized data from my cart session.
$order = new Order();
$order->cart = serialize($cart);
$order->code = strtoupper(str_random(15));
$order->user_id = Auth::user()->id;
$order->save();
now i need to unserialize the data to use it in my blade file, this is the function i'm using
$orders = Order::with('user')->findOrFail($order->id);
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
dd($orders);
I'm getting this error
BadMethodCallException Call to undefined method App\Order::transform()
what seems to be the problem? and how can i unserialize my data;
any ideas ???
With findOrFail you retrieve just one instance of model, not a collection.
$orders = Order::with('user')->findOrFail($order->id);
Also what is $order->id you have your order model?
So
$order->load('user');
$order->cart = unserialize($order->cart);
Or do you want a collection then your code will work like this
$orders = Order::with('user')->get();
$orders->transform(function($order, $key) {
$order->cart = unserialize($order->cart);
return $order;
});
The problem is not about unserialize, it doesn't even get there. The problem seems to be related to an undefined method you are trying to use ($orders->transform).
Can you please provide the code in your Order class? Did you define the transform method there?
EDIT:
by using serialize you are kinda' missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries.
Also, many tests prove that json_encode is faster than serialize.

Mysql Two table join Query not working in codeigniter

I want to integrate a two tables order and orderdetails table with an id of ord_id. My code is not working.
public function orderview()
{
$orderid = $this->uri->segment(3);
$data["order"]=$this->db->join('tbl__order', 'tbl__order_detail.ord_id = tbl__order.ord_id',$Query=' where ord_id='. $orderid);
$this->load->view('manage/orderpayment/view',$data);
}
Are you ever work with Codeigniter before?
Your Model function must look like this. Call this function from your Controller to return data, then you can process this data and send it to your View.
public function orderview(){
$orderid = $this->uri->segment(3);
$this->db->select('tbl__order.*, tbl__order_detail.ord_id as tbl__order_id');
$this->db->from('tbl__order');
$this->db->join('tbl__order_detail', 'tbl__order_detail.tbl__order_id = tbl__order.ord_id');
$this->db->where('tbl__order.ord_id', $orderid);
return $this->db->get()->result_array();
}
In "join" you can use as third argument left, right, outer etc.

How I can paginate DB::select(...) result and get links() method?

I have a big and difficult SQL query. It works fine for me. And I have the following code in the controller:
public function index(OpenRegDepDataReportInterface $openRegDepDataReport, Request $request): Renderable
{
$applications = $openRegDepDataReport->getReport($advertisers, $category);
return view('applications.index', compact('applications'));
}
So, the method getReport gives me a result of DB::select('<here is my big diffecult SQL>'), and, as well known it's an array.
But as you can see I'm trying to pass the result on a view. And, of course, I would like to call $applications->links() in the view, like for eloquent collection. Which is proper and faster way to do that?
doc
To display pagination at the table, you must call the select and then the pagination method.
in Controller:
$test = DB::table('users')->select('id')->paginate(10);
in View:
$test->links();
So based on the documentation if your $applications returns a Query Builder result, then just append ->paginate(10); to it.
https://laravel.com/docs/master/pagination#paginating-query-builder-results
$applications = $openRegDepDataReport->getReport($advertisers, $category)->paginate(10);
Simple answer, use paginate() method:
$basicQuery = DB::select(DB::raw("<here is the big diffcult SQL query>"));
However, paginate() works only on collections, and since you have an array of objects, you need to turn it into a collection first, using the forPage() method:
The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:
$collection = collect($basicQuery);
$chunk = $collection->forPage(2, 3);
$chunk->all();
Complicated answer: build a paginator instance yourself:
$perPage = 10;
$page = $request->input("page", 1);
$skip = $page * $perPage;
if($take < 1) { $take = 1; }
if($skip < 0) { $skip = 0; }
$basicQuery = DB::select(DB::raw("<here is the big diffcult SQL query>"));
$totalCount = $basicQuery->count();
$results = $basicQuery
->take($perPage)
->skip($skip)
->get();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page);
return $paginator;
I would recommend using the paginate() method.
You can read more about Laravel's pagination.

Codeigniter, how to pass COUNT result too my view

i have problem with passing data from model to my view. In Database i have Project with a few tasks i need to COUNT it. My problem is: How to pass the results to the view with foreach.
(echo $this->db->count_all_results(); in MODEL show good results)
Project 1: 5 tasks
Project 2: 10 tasks
Project 3: 1 task
MODEL:
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT( id_zadania ) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
return $query->result();
CONTROLLER
function WszystkieProjekty(){
$data['moje'] = $this->Todo_model->wyswietlWszystkieProjekty();
$arrayid = array();
foreach( $data['moje'] as $row ){
$row->id;
$aaa = $row->id;
$arrayid[] = $this->Todo_model->wyswietl($aaa);
}
$data['tabid'] = $arrayid;
$this->load->view('Projekty.html', $data);
}
MODEL:
function wyswietlWszystkieProjekty(){
$query = $this->db->query("SELECT * FROM todo");
return $query->result();
}
You're passing back to your controller a result set, so all you need to do is iterate over the result set, generating actual rows. It's not too hard, and you've got the right idea.
You have:
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT( id_zadania ) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
return $query->result();
As your model function that is supposed to return the count, right? Easiest way to do this is right from the model to keep your controller from having to do the legwork. When you run the count function in mysql, you'll only get back one row in your case, so using num_rows() isn't going to help because this query will always generate 1 row.
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT(id_zadania) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
$rs = $query->result();
return $rs[0]['COUNT(id_zaedania)'];
}
In your query, you have counted the data, so i think you can get the total data in the model from $query->rows()->zlics. And in the controller, just pass it to the view like usual
$data['moje'] = $this->Todo_model->wyswietlWszystkieProjekty(); $this->load->view('Projekty.html', $data);

Codeigniter search term with pagination

Still getting to grips with PHP and Codeigniter and I'm having an issue with passing a search term parameter from my Controller to my Model, with pagination.
I have a fully functioning script (with pagination) working already... However, trying to include the input post search term to the model is messing it all up (or I'm messing it all up).
Working script - Controller:
public function search()
{
$this->load->model('Products_model');
$config['base_url'] = base_url() . '/products/search/';
$config['total_rows'] = $this->db->count_all('affiliate_window');
$config['per_page'] = 25;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$data['offset_no'] = $this->uri->segment(3);
$data['items'] = $this->Products_model->get_search($config['per_page'], $data['offset_no']);
$this->load->view('header_view');
$this->load->view('products_view', $data);
$this->load->view('footer_view');
}
Working script - Model:
function get_search($limit, $offset)
{
$query = $this->db->get('mydb', $limit, $offset);
return $query->result();
}
So, any advice on how do I now go about passing $this->input->post('search_term'); from Controller to my model to use like this:
function get_search($limit, $offset)
{
$this->db->like('name', '$SEARCHTERM');
$query = $this->db->get('mydb', $limit, $offset);
return $query->result();
}
Furthermore, I believe I'm next going to run into an issue with keeping the search term variable throughout each page.
Any advice very welcome - I've been working on this for hours with no results! :)
So, understand that your pagination code & all the other code are "unrelated" - meaning, they don't require the other one to function.
You will pass your search term in to your model function like any other parameter & search on it in the query; limit & offset are simply tagged to the end of your query as you are doing now.
So if searching for "myterm", you'll just build a query with:
WHERE term = "myterm" LIMIT offset, limit
It's really quite simple once you get your head around what you are actually doing

Resources