Codeigniter 3 - Count rows from one table and join - php

I am trying to join two table and count all results from messageFiles which are related to message
I have tables with following structure:
messages:
id
name
email
subject
message
date_added
read
messagesFiles
id
name
message_id
date_added
I am trying this code, but I always get result countFiles = 1 and I message is repeated for every file that is related to it (for example if I have 3 files for the message, it will be repeated 3 times). Also messages which doesn't have files will not be selected by this query. What's seems to be a problem?
$this->db->select("SQL_CALC_FOUND_ROWS *, messages.*, COUNT(messagesFiles.id) as countFiles", FALSE)->from('messages')
->join('messagesFiles', "messagesFiles.message_id = messages.id")
->where("messages.read", 1)
->group_by('messagesFiles.id')->get()->result_array();

You could try some thing like this code below and add return $this->db->count_all_results().
http://www.codeigniter.com/docs
http://www.codeigniter.com/userguide2/database/active_record.html
public function count_test() {
$this->db->select("*");
$this->db->from('category c');
$this->db->join('category_description cd', "cd.category_id = c.category_id");
return $this->db->count_all_results();
}

Related

Codeigniter Complex MySQL Query

I got two table which I would like to query from, which the users table and the user_job table
users table structure
user_job table
What I want to achieve is to write a MySQL query in CodeIgniter to display user information from users table if user_status in users table is "Active" And if there is no row in user_job table where user_job_status is equal to "On Probation" or user_job_status is equal to "Active"
In simple English, I want to display a user information if a user not currently on a job.
My current Codeigniter Model code is:
//get all user that are not currently assigned to a position
function get_idle_user(){
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_job', 'user_job.user_id_fk = users.user_id', 'INNER');
$this->db->where('users.user_status','Active');
$this->db->where("(user_job.user_job_status != 'Active' OR user_job.user_job_status != 'On Probation')", NULL, FALSE);
$this->db->group_by('users.user_id');
if($query = $this->db->get()){
return $query;
}else{
return false;
}
}
The problem with this code that it will still display user information if there is a row related to a user and user_job_status does not satisfy the where condition above.
Please Help.
I believe this is what you are after ...
$db->select('user_id_fk,COUNT(*) as `Tally`');
$db->where('user_job_status','On Probabtion');
$db->or_where('user_job_status','Active');
$db->group_by('user_id_fk');
$sub = $db->get_compiled_select('user_job_table');
$db->join("($sub) ujt",'ujt.user_id_fk = users.user_id AND Tally = 0','left');
$db->where('user_status','Active');
// View this query in full
//echo $db->get_compiled_select('users_table');
// Get the data
$data = $db->get('users_table')->result_array();
Note:
You don't need select('*') - it isn't needed
You don't need ->from() - it can be used in the get() element
I have left in the get_compiled_select which will allow you to see the full query and get an idea what its doing. You should comment out the $data line if you uncomment the echo line.
What this query is doing is saying get all users from the job_table which don't have the status Active or On Probation and a list of User ID's. That way you can then get Active users from the users_table and users with a tally of 0.

Laravel : Select and GroupBy SQL Query Error. Multiple Selects with groupBy? Is it Possible?

I have an 2 tables Ratings and Attributes , i pass the month and get all record of both users and count this , i have already count this record , and divided into groups by user_id , But in my attribute table i have a user name , and join this table to get attribute name , My query is that
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw("SUM(ratings.attribute_score) as score"))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('ratings.user_id')
->get();
dd($records);
And get json like that
But i want to get name of the specific user with score but here multiple selects not working in this query how to use multiple select to get attributes table records? if i am using this query. Thanks Developers in advance
->select(DB::raw("SUM(ratings.attribute_score) as score , ratings.user_id , attributes.attributes_name"))
Using this the select not working here it always return the score Jason like show in the Sceenshot. How can i do to selects multiples using groupBy??
USE THIS TO GET USERNAME WITH SCORE COUNTS. Try This
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw('SUM(ratings.attribute_score) as score, users.name as
user_name'))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('users.name')
->get();
return view('attribute.show' , compact('records'));

Codeigniter JOIN - not a unique table/alias issue

I have bookings tables from several countries (for example: book_uk) these tables contain information about our customers in different countries such as name, address, etc etc. Then in my results table I have the results of all tests this customer has had, the information is 'linked' by a PIN number, eg 336699, this number is referenced in both the book_uk table and the results table.
What I want to do is select all data from the book_uk table and then link each row to the results table (where the PIN matches) but I keep getting not a unique table/alias, here is my model code:
$database->select($new_country_columns)
->from($country_table);
$database->select($p_results_cols)
->from($table);
$database->join('p_results', $join, 'inner');
$database is defined earlier on in the model
Produces this error:
Error Number: 1066
Not unique table/alias: 'p_results'
SELECT `book_uk`.`pin`, `book_uk`.`clinic`, `book_uk`.`dob`, `book_uk`.`gender`, `book_uk`.`country`, `book_uk`.`order_date`, `p_results`.`pin`, `p_results`.`code`, `p_results`.`name`, `p_results`.`result` FROM (`book_uk`, `p_results`) INNER JOIN `p_results` ON 'book_uk.pin = p_results.pin'
Filename: C:/xampp/htdocs/projects/b2k-stat/system/database/DB_driver.php
Line Number: 691
what I really need to do is select data from book_uk and then run a foreach loop on the results table and add any data with matching PIN to the results array, I have no idea how to do this, I tried to loop through it with a foreach loop but it kept coming up blank, i've also tried:
$database->select($new_country_columns)
->from($country_table)
->join('p_results', $join, 'inner');
But this also gives me zero results, any help? Thanks in advance
Remove
'p_results'
from your
FROM
clause since your joining it right after that.
Not sure if this is the best way to do things, but I solved my issue by generating 2 queries and running an IF statement inside a foreach loop on both queries like so:
$database->select($new_country_columns)
->from($country_table);
$query1 = $database->get()->result_array();
$p_results->select($p_results_cols)
->from($table);
$query2 = $p_results->get()->result_array();
foreach($query1 as $row){
foreach($query2 as $rows) {
if($row['pin'] === $rows['pin']) {
$new_row = array_merge($row, $rows);
$query[] = $new_row;
}
}
}
return $query;
This code gave me an array of the combined data that was needed to display in my view

Grocery Crud - Can't differentiate attribute in returning query table

I've been using Grocery Crud to develop a simple local application that allows users to register themselves and like bands and rate them and select people they know that are also registered in the application.
Entities:
Person(person_id,person_URL, fullname, hometown)
Band(band_id,band_URL,band_name,country,genre)
Relationships:
Likes(person_id,band_id,rate)
Knows(person_id,known_person_id)
My questions are:
1) I want to return a table of person and known person like below:
KNOWS
person_id | fullname | known_person_id | known_fullname
but I can't use *set_relation_n_n* function 'cause the relationship is (Person -> Likes -> Person), so it's giving me error. The other solution I came up with is making a custom table making a query to return the values I want and show it in the table (code below). The custom table returned is correct but when I render it to my Grocery Crud table, I need to specify $crud->columns('person_id', 'fullname', 'known_person_id', 'fullname'), and it cannot differentiate the fullname of the person and the fullname of the known person. How would I make it in order to be able to show the table that way?
2) I have the same issue in another table but could manage that using the function *set_relation_n_n* 'cause it's a relationship (Person -> Likes -> Band), so since it's 2 different entities it didn't return me a error. The problem is that the query (code below) returns me the whole table and I want only 25 records per page. When I try to use "LIMIT 25" in the query, it returns me ONLY 25 records and the "next page" button doesn't work. Any solutions?
Below, all the information:
CODE for question 1:
function knows_management()
{
$crud = new grocery_CRUD();
$crud->set_model('model_socialnetwork');
$crud->set_table('knows');
$crud->set_subject('Known');
$crud->basic_model->set_query_str('SELECT tb1.person_id, tb1.fullname, tb1.known_person_id, person.fullname FROM (SELECT person.person_id, person.fullname, knows.known_person_id FROM person INNER JOIN knows ON person.person_id = knows.person_id) tb1 INNER JOIN person ON tb1.known_person_id = person.person_id');<br>
$crud->columns('person_id','fullname','known_person_id','fullname');
$output = $crud->render();
$this->_socialnetwork_output($output);
}
CODE for question 2:
function likes_management()
{
$crud = new grocery_CRUD();
$crud->set_model('model_socialnetwork');
$crud->set_table('likes');
$crud->set_subject('Like');
$crud->columns('person_id','fullname','band_id','band_name', 'rate');
$crud->basic_model->set_query_str('SELECT tb2.person_id, tb2.fullname, tb2.band_id, band.band_name, tb2.rate FROM(SELECT tb1.person_id, person.fullname, tb1.band_id, tb1.rate FROM(SELECT person.person_id, likes.band_id, likes.rate FROM person INNER JOIN likes ON person.person_id = likes.person_id) tb1 INNER JOIN person ON tb1.person_id = person.person_id) tb2 INNER JOIN band ON tb2.band_id = band.band_id');
$output = $crud->render();
$this->_socialnetwork_output($output);
}
Question 1) What if you use an alias name in your query, for example
SELECT tb1.person_id, tb1.fullname as Tb1fullName, tb1.known_person_id, person.fullname as PersonFullName
Question 2) I would not recommend you to add LIMIT directly / manually in your query. In the file application/config/grocery_crud.php, you have two options directly related to pagination
You should use and configure them properly
// The default per page when a user firstly see a list page
$config['grocery_crud_default_per_page'] = 25;
....
//Having some options at the list paging. This is the default one that all the websites are using.
//Make sure that the number of grocery_crud_default_per_page variable is included to this array.
$config['grocery_crud_paging_options'] = array('10','25','50','100');

Codeigniter active record left join issue

I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns

Categories