I am currently using Codeigniter. As shown below, a query looks up for the count of rows and then sent it to the view. However, the view does not shows the actual count. The actual count on DB (InnoDB) is 1001 but displays up to 1000 on my view. Any ideas?
Model:
public function check_source_email($location){
$query="SELECT COUNT(*) as row_count FROM feedback WHERE location = '$location' AND source_lead = 'Email' ";
$count=$this->db->query($query)->result();
return $count[0]->row_count;
}
Controller:
$data['email'] = $this->Stats->check_source_email($location);
View:
<strong>Email Listing</strong><span class="pull-right"><?php echo $email; ?></span>
Use num_rows:
public function check_source_email($location){
$query = $this->db->get_where('feedback',array('location'=>$location,'source_lead'=>'Email'));
return $query->num_rows();
}
First, I would try and do things the codeigniter way, if you are working with codeigniter:
public function check_source_email($location) {
return $this->db
->where('location', $location)
->where('source_lead', 'Email')
->count_all_results('feedback');
}
That theoretically should return the correct result, although I'm not sure why your original didn't, but maybe this will fix it.
Related
I am using Laravel 5 with vue js. Basically i am fetching data using axios and trying to display on the webpage using vue js v-for directive.
i have tables in database like this:
ratings Table
id review_id rating
Then i have a
reviews table
id review
They have one to many relationship between. so here in my Review Model i have method
public function ratings()
{
return $this->hasMany('App\Rating')
->selectRaw('review_id,AVG(rating) AS average_rating')
->groupBy('review_id');
}
so here i want to fetch list of reviews with their average ratings. so in my controller i am doing this:
public function getAllReviews(Request $request)
{
$reviews = Review::with('ratings')->get();
return $reviews;
}
So i am getting result but the problem is every review doesnt have ratings record so it is returning null? maybe...
when i try to render in vue template it throws an error undefined because in our collection some reviews do not have ratings.
Now my question is: Can i do something like if there is no record in the ratings for a particular review is it possible to add an array with value 0?? so in my frontend it wont see as undefined.
I hope i am successful to explain i am trying.
Thank you.
You may do it this way:
public function getAllReviews(Request $request)
{
$reviews = Review::selectRaw('*, IFNULL((SELECT AVG(rating) FROM ratings where ratings.review_id = reviews.id), 0) as avg_rating')->get();
return $reviews;
}
I would suggest using the basic relationship and a modified withCount():
public function ratings() {
return $this->hasMany('App\Rating');
}
$reviews = Review::withCount(['ratings as average_rating' => function($query) {
$query->select(DB::raw('coalesce(avg(rating),0)'));
}])->get();
public function showProduct($id)
{
$data = Product::where('category_id',$id)
->selectRaw('*, IFNULL((SELECT AVG(value) FROM ratings where ratings.product_id = products.id), 0) as avg_rating')
->get();
return view('ecommerce.web.productsOfcategory',compact('data'));
}
$avgQuery = "IFNULL((SELECT AVG(ratings.rating) FROM ratings WHERE ratings.review_id = reviews.id),'No Ratings') as avg_rating";
$reviews = Review::query()->selectRaw("reviews.*, $avgQuery")->get();
//SQL Query
$sqlQuery = "select reviews.*, IFNULL((SELECT AVG(ratings.rating) FROM ratings where ratings.review_id= ratings.id), 'No ratings') as avg_rating FROM reviews";
I tried to fetch data using joins and the data is repeating,
The controller code is:
public function searchjobs2()
{
//$id=$_SESSION['id'];
$lan = $_POST["picke"]; //var_dump($id);die();
$value['list']=$this->Free_model->get_jobs($lan);//var_dump($value);die();
$this->load->view('free/header');
$this->load->view('free/searchjobs2',$value);
}
And the model:
public function get_jobs($lan)
{
$this->db->select('*');
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work.login_id = tbl_work_stats.login_id",'inner');
$this->db->where("language LIKE '%$lan%'");
// $this->db->where('tbl_work_stats.login_id',$id);
$this->db->order_by('insertdate','asc');
$query=$this->db->get()->result_array();//var_dump($query);die();
return $query;
}
I have used
foreach ($list as $row){
...
}
for listing.
Using distinct will remove duplicate fields:
$this->db->distinct();
From what I can see, your query has ambiguity, and an error in the join statement, also your where like is part of the problem, I would recommend trying this even do there are some missing info, find out wich field you need to join from the second table.
public function get_jobs($lan){
$this->db->select("tbl_work_stats.*, tbl_work.fields");
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work_stats.login_id = tbl_work.login_id","inner");
$this->db->where("tbl_work.language LIKE", "%" . $lan . "%" );
$this->db->order_by("tbl_work_stats.insertdate","asc");
$query=$this->db->get()->result_array();
return $query;}
do you mean to join on login_id?
I am guessing that is the user logging in and it is the same for many entries of tbl_work_stats and tbl_work.
you didn't post your schema, , but login_id doesn't seem like right thing to join on. how about something like tbl_work.id = tbl_work_stats.tbl_work_id or similar?
also CI $db returns self, so you can do:
public function get_jobs(string $lan):array
{
return $this->db->select()
->from('tbl_work_stats')
->join('tbl_work','tbl_work.id = tbl_work_stats.work_id')
->like('language',$lan)
->order_by('insertdate')
->get()
->result_array();
}
I'm trying to find a number of UserComment using a viaTable on the table called user_comment_user in Yii2. However I can't seem to get my variables/query inserted properly.
Currently I've got two queries set up, to check if (on their own) they achieve the correct result, which they do.
These are the two queries that somehow have to be merged into one:
public function findConversation($id)
{
$query = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['sender_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['receiver_id'=>$id]);
});
$query2 = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['receiver_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['sender_id'=>$id]);
});
return $query;
}
The answer was actually much simpler than I had imagined:
public function findConversation($id)
{
$query = UserComment::find();
$query->leftJoin('user_comment_user', 'user_comment_user.user_comment_id=user_comment.id');
$query->where(['receiver_id'=>$this->id, 'sender_id'=>$id]);
$query->orWhere(['receiver_id'=>$id, 'sender_id'=>$this->id]);
$query->orderBy(['created_at'=>SORT_DESC]);
return $query;
}
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. :)
I am working in codeigniter.. I want to count the no. of rows having the same order_no.. below is my code.
public function get_my_orders() {
$user_data = $this->session->all_userdata();
$email = $user_data['user_email'];
$this->db->select('*');
$this->db->from('order_details');
$this->db->where('email', $email);
$this->db->group_by('order_no');
$this->db->order_by('order_no', 'DESC');
$query = $this->db->get();
return $query->result();
}
Pls help..
You can use $this->db->count_all_results()
public function get_my_orders() {
$user_data = $this->session->all_userdata();
$email = $user_data['user_email'];
//$this->db->select('*');// no need select as you only want counts
$this->db->from('order_details');
$this->db->where('email', $email);
//$this->db->group_by('order_no');//no need group_by as you only want counts
//$this->db->order_by('order_no', 'DESC');//no need order_by as you only want counts
return $this->db->count_all_results();;
}
Try changing your select line to look like this:
$this->db->select('COUNT(*) as count');
Rather than having all fields accessible like they currently are, you will instead only have access to one variable called count. To keep all variables accessible and add the count in as well, use this instead:
$this->db->select('*, COUNT(*) as count');
Feel free to change the lowercase name for count, I'm just using that as an example.
Check Codeigniter Manual
$query = $this->db->get();
return $query->num_rows(); //Return total no. of rows here
$query->num_rows(); will count the total active record return by your query.