Codeigniter dynamic pagination and where_not_in - php

So I have a function in my model which pulls through jobs for a paginated table but only if they have not been booked.
My first function counts the results for how many pages there are etc.
function record_count() {
$this->db->select('id');
$this->db->from('jobs');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
return $this->db->count_all("jobs");
}
My second actually brings in the jobs.
function getPagedJobs($limit, $start){
$this->db->limit($limit, $start);
$grabPagedJobs = $this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE)->get("jobs");
if ($grabPagedJobs->num_rows() > 0) {
foreach ($grabPagedJobs->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
The problem is that the second function gets the jobs fine, and doesn't display the ones that are booked. But the first function which counts the pages still seems to count all the results, even the booked ones. Thus giving me empty pages and PHP invalid arguments on my paginated results.
I've messed around with a lot of ways, and would prefer active record if possible but I had no success with that.
Thanks,

You have a wrong statement here,
return $this->db->count_all("jobs");
count_all("jobs") will give you number of rows in jobs table.
Replace it with this -
return $this->db->count_all_results("jobs");
Read documentation - http://ellislab.com/codeigniter/user-guide/database/active_record.html
OR an alternative method for count in ci,
$this->db->select('COUNT(*) as count');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
$query = $this->db->get('jobs');
$result = $this->db->result($query);
return $result->count;

In your implementation you are using function $this->db->count_all which counts all rows in a table.
If you want to count the number of rows in your particular query, you should use $this->db->count_all_results function. Correct implementation is:
function record_count() {
$this->db->select('id');
$this->db->from('jobs');
$this->db->where('`id` NOT IN (SELECT `jobs_id` FROM `jobs_user`)', NULL, FALSE);
return $this->db->count_all_results("jobs");
}

Related

MySQL request return null Controller PHP

I've create a table order on my code, My idea is to generate an Unique order Id per user.
On my controller I have a code with the MYSQL request, and a function to return the result (which works on other SQL requests).
So My idea is on MySQL request is to count the number of order with the same number and If result is =1 I have to generate a new order number. On my order class I have this function:
public static function getCountOrderIfExist($bdd, $order_number) {
$requete = "SELECT * FROM Order WHERE order_number='$order_number'";
$commandes = getResultatRequete($bdd, $requete);
return !empty($commandes) ? $commandes : null;
}
And I call it on my Controller:
$count = Order::getCountOrderIfExist($bdd, $order_number);
while ($count >= 1) {
$order_number= $user_role."_".$user->getUtilisateurId().rand(1,99999)."_".$user->getEntreprise()->getId().rand(1,999999);
}
And here is the code of my getResultatRequete:
function getResultatsRequete(PDO $bdd, $requete) {
$reponse_requete = $bdd->query($requete);
if ($reponse_requete != false) {
$resultat_requete = $reponse_requete->fetchAll();
return str_replace("\\", "", $resultat_requete);
} else {
printErrorInfo($bdd, $requete, true);
return array();
}
}
When I run my code on debug mode the SQL request return NULL and I don't understand why, because when I run my Request on a terminal it works well. Any idea?
From our correspondence in the comments, it seems that the problem lies in the return statement:
return !empty($commandes) ? $commandes : null;
That statement returns any found records, or null if no records are found. However, it seems that the controller expects the function to return the number of matching records (0 if none are found).
In order to return a number for you to work with, you need to instead do a count of the returned records:
return count($commandes);
This should give you the results you need.

Return count on an eager-loaded relation Laravel

So I have Subject that contains Stack, which contain Question. With every question, there are answers, and I would like to count the answers on every Stack, but I'm stuck.
This is what I'm trying to do, one of many solutions I have been fiddling with:
$subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();
return $subjects;
The Subject model has the following relation:
public function stack(){
return $this->hasMany(Stack::class);
}
And if we look at the Stack model on how the relations are built:
public function question(){
return $this->hasMany(Question::class);
}
public function answers(){
return $this->hasMany(Answers::class);
}
public function answersCount(){
return $this->answers()->selectRaw('answer, count(*) as aggregate')->groupBy('answer');
}
But when I return $subjects, answer_count is empty.
"answers_count": []
It's very confusing because when I run the same query in SQL, I get non-empty results.
select answer, count(*) as aggregate from `answers` where `answers`.`stack_id` in ('1', '6') group by `answer`
correct 9
wrong 4
So how can I count all answers? And group them?
try this way,
$subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();
$count = $subjects->answersCount->first()->aggregate;
//count varible will have the count now you can use it as you would like to
return $subjects;
Further digging can be found here
Remove answersCount relation - it's not necessary anymore, since you can use withCount method:
$subjects = Subject::with([
'stack.question',
'stack' => function ($q) {
$q->withCount('answers');
}
])->get();
// then on each subject you can call stack->answers_count
$subjects->first()->stack->answers_count

Doctrine 2 - Get total when using limit via repository

I'm new to Doctrine, and I just could not find a way to get the total number of results when using limit with Criteria (via setMaxResults function) in the EntityRepository::matching method.
In my repository (not an extend of EntityRepository), I'm using the following (I know this is not the optimal code, it is used just to learn Doctrine):
public function getAll($query = null) {
if ($query instanceof Criteria) {
$users = $this->em->getRepository('App\Entities\User')->matching($query)->toArray();
} else {
$users = $this->em->getRepository('App\Entities\User')->findAll();
}
return $users;
}
Now lets say that the Criteria is defined like so:
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
$query->setMaxResults(10);
And there are actually more than 10 users that match that.
How can I get the total number of the users that match the criteria?
If you set maxResults to 10, you get 10 results ;).
Why don't you call getAll() to get all results and apply the MaxResults later?
//search for Ron's
$query = Criteria::create();
$query->where(Criteria::expr()->contains('username', 'ron'));
//check how many Ron's your database can find
$count = $repo->getAll($query)->count();
//get the first 10 records
$query->setMaxResults(10);
$users = $repo->getAll($query);

Only last row getting displayed in view in Codeigniter

I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)

How to use limit correctly in Codeigniter Framework PHP

In my project I want to show 3 rows, for which i use limit('3'), but when my result is greater then 3, content is not showing.
if i limit increase from 3 to 5 or 6 then items again start to show.
how to fixed this problem, so that if item count is more, it shows just 3?
Here is database code, written into Model:
public function select_all_contenta()
{
$this->db->select('*');
$this->db->from('content');
$this->db->order_by('date_add','DESC');
$this->db->limit('3');
$query_result=$this->db->get();
$allcontent_infoa=$query_result->result();
return $allcontent_infoa;
}
public function select_all_contenta() {
$this->db->from('content');
$this->db->order_by('date_add','DESC');
$this->db->limit('3');
$query_result = $this->db->get();
$allcontent_infoa = $query_result->result_array();
return $allcontent_infoa;
}
change
$this->db->limit('3');
into
$this->db->limit ( 3 );
It should be number not string value (limit the number of rows you would like returned by the query)
Try to change this code
$this->db->limit(2,0); //$this->db->limit(3,0);
your code is not optimised.
try this instead
public function select_all_contenta()
{
$q = $this->db->get('content' , 3)->order_by('date_add','DESC');
return $q->result();
}

Categories