Codeigniter select_avg('columnname') WHERE thisaverage > x - codeigniter

What I want to do is select items from my database where the average review is greater than 7.
$this->db->select_avg('reviews.overall');
That query selects the average review 'as overall'.
Therefore i assumed i could simply then use
$this->db->where('overall>','7');
This however does not work.
ANy ideas?
Thanks
EDIT
Putting in a space
$this->db->select_avg('reviews.overall');
$this->db->where('overall >','7');
Yields the error
Column 'overall' in where clause is ambiguous
It is ambiguous but how am I now meant to reference it??
Thx

It's writen in the codeigniter user manual too:
$this->db->select_avg(); Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
If you enable profiler in CI, you would see, what query does this code generate.
Your code is generated like this:
SELECT AVG(reviews.overall) as reviews.overall FROM ....
Use it like this:
$this->db->select_avg('reviews','overall');
$this->db->from('table name');
$this->db->where('overal >', 7);
$Q = $this->db->get();

Related

laravel unique() dont work with paginating

i'm facing with an issue in laravel 5.7.28, i'm trying to get records with all of my fields and paginate them , sadly i got a bug in my code that cause registering users with duplicate phone number(a user registered itself more than one time and of course i fix the bug ) , for now i'm facing with a scenario that i want to fetch my (non-duplicate) distinct users on their phone, and paginate them . here is wishful scenario :
$users = User::distinct('phone')
->doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()->paginate(40);
it returns all users (with duplicate phone number), seems distinct function not affected , so i tried unique function :
$users = User::doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()->paginate(40)->unique('phone');
it works (for getting non-duplicate) but break paginating functionality
and for
$users = User::doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()
->unique('phone')
->paginate(40);
i got error for undefined function on builder , means it works on collections ,
also i tried groupBy (search whole the web for solution) , it makes me confused till when i use it
User::doesntHave('carrierUsers')->doesntHave('thirdparty')
->latest()->groupBy('phone')
->paginate(40);
i got SELECT list is not in GROUP BY clause, is that mean in every phrase in my select statement (for now is all ('*') ) i should use it in my groupBy ?
i mean i need all columns , how can i have all those column in groupBy clause ? whats that mean by the way ?
, error is telling : this is incompatible with sql_mode=only_full_group_by. is she making this happen ? how can i fix it ?
1) excuse me for my english
2) Thanks for reading whole this
3) pleasure to reply and help me
Problem 1: Use distinct
For distinct() method, passing parameters is not supporteds, so distinct(phone) will not works.
You can use ->select('phone')->distinct() instead. However, support unique column is selected.
Problem 2: Use Group By
So if you want to select all columns and unique one column, you can use group by.
And because you are using mysql 5.7+.
The ONLY_FULL_GROUP_BY and STRICT_TRANS_TABLES modes were added in MySQL 5.7.5.
So if you select all columns and group one column, you will get the only_full_group_by error.
There are two options can solve this problem.
Solution1:
Use ANY_VALUE()
User::doesntHave('carrierUsers')->doesntHave('thirdparty')
->latest()
->selectRaw('phone, ANY_VALUE(id) AS id, ANY_VALUE(username) AS username, ...')
->groupBy('phone')
->paginate(40);
Solution2:
In config/database.php configuration, set strict mode to false(This is not very safty):
'mysql' => [
'driver' => 'mysql',
...
'strict' => false,
],

CodeIgniter Count Records for Query that Excludes Limit Condition

I want to do two things in one query: use the limit() function, but also get the total number of records as a record count for the query, as if the limit wasn't used. So, if there are 21 total records that meet the conditions like '%Gregory%', I would like that value returned, even though I'm using a limit(10,0).
Here's my code:
$data['recordcount'] = $this->db->count_all_results('assets');
$this->db->limit(10, 0);
if(isset($data['order'])){
$query = $this->db->select('*')->from('assets')->or_like($array)->order_by($column, $data['order'])->get();
}
The problem is that $data['recordcount'] in the first line returns all records. I want it to return all records that meet the query condition in the 4th line, but without the limit found in the 2nd line.
Normally count_all_results() clears the select statement when run. But by setting the second parameter to FALSE the statement is retained.
I think this will work for you.
$this->db->select('*')->from('assets')->or_like($array);
$data['recordcount'] = $this->db->count_all_results('assets', FALSE);
$this->db->limit(10, 0);
if(isset($data['order']))
{
$this->db->order_by($column, $data['order']);
}
$query = $this->db->get();
You can achieve SQL_CALC_FOUND_ROWS before the asterisk (*) like this:
$this->db->select('SQL_CALC_FOUND_ROWS *')->from('assets')..etc
This will calculate the number of rows that would be returned without the LIMIT condition.
Immediately after that you can select the FOUND_ROWS() like this:
$this->db->select('FOUND_ROWS()')->get();
This will return you the number you are looking for.
For more information refer to this page
enter link description here

How to combine and & or operators in grocery crud

I am using codeigniter and grocerycrud, I want to set a table with grocerycrud in this way:
SELECT * FROM `dashboard`.`medidas_ludlum`
where FK_ludlum='190.26.88.131'
and date>= '2014-03-04 09:40:00'
and date<= '2014-03-05 09:40:00'
and (error_code=1 or audio_status=1);
I tried to do that in this way:
$uno='1';
$crud2 = new grocery_CRUD();
$crud2->set_theme('datatables');
$crud2->where('FK_ludlum',$ludlum_id);
$crud2->where('date>=',$fechainicio);$crud2->where('date<=',$fechafin);
$crud2->where('error_code =',$uno);
$crud2->or_where('audio_status =',$uno);
$crud2->set_table('medidas_ludlum');
$crud2->columns('measurement', 'fecha', 'audio_status', 'high_alarm_status', 'low_alarm_status','over_range_status','monitor_status','error_code');
$crud2->set_language("spanish");
$crud2->unset_add();$crud2->unset_delete();$crud2->unset_edit();$crud2->unset_read();
$data['crud2'] = $crud2->render();
However it's not giving the right results, for example I am getting rows that have a date out of the range, is there a way to get that CRUD set up?
Grocery curd is also using codeigniter's active record so you can write your where() with grouped conditions as below,no need to use or_where() function
$crud2->where('(error_code ='.$uno.' OR audio_status ='.$uno.')',null,FALSE);
or
$crud2->where('(error_code =1 OR audio_status =1)',null,FALSE);
The problem in your query is when you use or_where() function it produces where clause as and error_code=1 or audio_status=1 and using approach that i have provide will give you the where clause as and (error_code=1 or audio_status=1) a grouped condition
API and Functions list

Short table name for SQL Query with Codeigniter database library

I'm using CodeIgniter, I want to using short table name for my SQL Query like that:
select pr.name from product pr where pr.id=12;
by using db class, I supposed to do:
$this->db->select('pr.name')->from('product pr')->where('pr.id', 12)->get();
This works perfect on CI 2.1.3. Don't forget to use result().
Example works for me:
function test(){
$this->load->database();
$sql = $this->db->select('pr.order_id')->from('items_table pr')->where('pr.order_id', 2)->get();
foreach($sql->result() as $item){
echo $item->order_id;
}
}
You can do it in this form:
$this->db->select('pr.name');
$this->db->from('product as pr');
$this->db->where('pr.id', 4);
return $this->db->get()->row_array();
with row_array() you will get one row, with result_array() you will get result of array.
There are so many solutions.. I prefer HMVC, but for demo purpose to explain "how it works", solutions inside controller (terrible,sucks!!!!)
Answer for using shorts table as alias, pls read rtfm or use simple query and generating results
For join methods,you can use too. Happy coding

Mulitple LIKE db query using associative array- but all from the same column name...?

I'm trying to query my database using CodeIgniter's active record class. I have a number of blog posts stored in a table. The query is for a search function, which will pull out all the posts that have certain categories assigned to them. So the 'category' column of the table will have a list of all the categories for that post in no particular order, separated by commas, like so: Politics, History, Sociology. etc.
If a user selects, say, Politics, and History, The titles of all the posts that have BOTH these categories should be returned.
So, the list of categories queried will be the array $cats. I thought this would work-
foreach ($cats as $cat){
$this->db->like('categories',$cat);
}
By Producing this:
$this->db->like ('categories','Politics');
$this->db->like ('categories','History');
(Which would produce- 'WHERE categories LIKE '%Politics%' AND categories LIKE '%History%')
But it doesn't work, it seems to only produce the first statement. The problem I guess is that the column name is the same for each of the chained queries. There doesn't seem to be anything in the CI user guide about this (http://codeigniter.com/user_guide/database/active_record.html) as they seem to assume that each chained statement is going to be for a different column name.
Of course it is not possible to use an associative array in one statement as it would have to contain duplicate keys- in this case every key would have to be 'categories'...
With regard to MySQL, I just ran the following query on my database and there were no issues.
SELECT *
FROM `TicketUpdates`
WHERE content LIKE '%update%'
AND content LIKE '%footprints%';
Likewise the following code ran as expected:
$this->db->select('*');
$this->db->from('TicketUpdates');
$this->db->like('content', 'update');
$this->db->like('content', 'footprints');
print_r($this->db->get()->result());
If you're using the 'like' function in CI, you have to prefix and postfix them with the proper query functions, example:
$this->db->select('*');
$this->db->from('tablename');
foreach($cats as $cat){
$this->db->like('categories', $cat);
}
$result = $this->db->get();
you can use following code
$this->db->select("*")->from($table);
foreach($cats as $single_name)
$this->db->or_like("categories",$single_name);
$result = $this->db->get();

Resources