I have composed a query using Codeigniter's Query Builder class. The query utilizes aliases and the having method. When I call the count_all_results method on this query, an exception occurs. Inspecting the log, I see that the query has stripped out the 'having' clauses. Is there a way to keep these clauses in while calling count_all_results? Thanks for your help.
EDIT: I first believed the problem was knowledge-based and not code-based and so did not share the code, but here it is. Please let me know if more is needed.
Here's the call on the model in the controller.
$where_array = array(
$parent_key.' is not NULL' => null
);
$search_post = $request_data['search'];
if (isset($request_data['filter'])) {
$filter_array = $request_data['filter'];
foreach ($filter_array as $filter_pair) {
if (isset($filter_pair['escape'])) {
$where_array[$filter_pair['filterBy']] = null;
} else {
if ($filter_pair['filterBy'] == 'table3_id') {
$where_array['table3.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
} else {
$where_array[$table.'.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
}
}
}
}
$like_array = array();
foreach ($request_data['columns'] as $key => $column) {
if (!empty($column['search']['value'])) {
$like_array[$column['data']] = $column['search']['value'];
}
}
$totalFiltered = $this->$model_name->modelSearchCount($search, $where_array, $like_array);
Here's the model methods.
public function modelSearchCount($search, $where_array = null, $like_array = null)
{
$this->joinLookups(null, $search);
if ($where_array) {
$this->db->where($where_array);
}
if ($like_array) {
foreach($like_array as $key => $value) {
$this->db->having($key." LIKE '%". $value. "%'");
}
}
return $this->db->from($this->table)->count_all_results();
}
protected function joinLookups($display_config = null, $search = null)
{
$select_array = null;
$join_array = array();
$search_column_array = $search ? array() : null;
$i = 'a';
$config = $display_config ? $display_config : $this->getIndexConfig();
foreach ($config as $column) {
if (array_key_exists($column['field'], $this->lookups)) {
$guest_model_name = $this->lookups[$column['field']];
$this->load->model($guest_model_name);
$join_string =$this->table.'.'.$column['field'].'='.$i.'.'.
$this->$guest_model_name->getKey();
$guest_display = $this->$guest_model_name->getDisplay();
if ($search) {
$search_column_array[] = $i.'.'.$guest_display;
}
$join_array[$this->$guest_model_name->getTable().' as '.$i] = $join_string;
$select_array[] = $i.'.'.
$guest_display;
} else {
$select_array[] = $this->table.'.'.$column['field'];
if ($search) {
$search_column_array[] = $this->table.'.'.$column['field'];
}
}
$i++;
}
$select_array[] = $this->table.'.'.$this->key;
foreach ($join_array as $key => $value) {
$this->db->join($key, $value, 'LEFT');
}
$this->db->join('table2', $this->table.'.table2_id=table2.table2_id', 'LEFT')
->join('table3', 'table2.table3_id=table3.table3_id', 'LEFT')
->join('table4', $this->table.'.table4_id=table4_id', 'LEFT')
->join('table5', 'table4.table5_id=table5.table5_id', 'LEFT');
$this->db->select(implode($select_array, ', '));
if ($search) {
foreach (explode(' ', $search) as $term) {
$this->db->group_start();
$this->db->or_like($this->table.'.'.$this->key, $term);
foreach ($search_column_array as $search_column) {
$this->db->or_like($search_column, $term);
}
$this->db->group_end();
}
}
$this->db->select('table2_date, '. $this->table.'.table2_id, table4_id, '. 'table5.table5_description');
}
Since count_all_results() will basically run a Select count(*) and not count the rows in your resultset (basically rendering the query useless for your purposes) you may use other Codeigniter methods to get the resultset and the row count.
Try running the query into a variable:
$query = $this->db->get();
From then, you can do pretty much anything. Besides returning the result with $query->result(); you can get the number of rows into another variable with:
$rownum = $query->num_rows();
You can then return that into your controller or even just return the $query object and then run the num_rows() method on the controller
To answer this question, count_all_results() transforms the original query by replacing your selects with SELECT COUNT(*) FROM table. the aliased column would not be selected, and the having clause would not recognize the column. This is why count_all_results() does not work with having.
Related
let's say i have this query:
$schedules = [33,34];
foreach ($schedules as $schedule) {
$buses[] = DB::table("buses")->select('id', 'bus_number')
->where('station_id', $stations_id)
->whereNotNull('Driver_id')
->get();
}
The data it is returning is empty like this: [[],[]]
So, my question Is how to check if there is data in it or not?
A simple solution would be excluding null filled values:
$schedules = [33,34];
foreach ($schedules as $schedule) {
$bus = DB::table("buses")->select('id', 'bus_number')
->where('station_id', $stations_id)
->whereNotNull('Driver_id')
->get();
if($bus && isset($bus->id)) {
$buses[] = $bus;
}
}
if($buses && count($buses)>0) {
//has value
}
If you have related Schedule with buses, you could use, something like this;
$schedules = Schedule::whereIn('id',$schedule_ids)->with('buses')->get();
//and you dont need to set into an array
You could use count() funcion, something like this:
$schedules = [33,34];
foreach ($schedules as $schedule) {
$bus = DB::table("buses")->select('id', 'bus_number')
->where('station_id', $stations_id)
->whereNotNull('Driver_id')
->get();
if(count($buses) > 0) {
$buses[] = $bus;
}
}
After insert I want to update field with ($id.'mytext') where in db that field is empty for all rows.
table name: peca
columns:
id -autoincrement
A -varchar user insert
CB -varchar auto insert with update
MODEL WILL RETURN ALL ROWS WHERE CB=empty
function model1() {
$this->db->select('*');
$this->db->from('peca');
$this->db->where('CB', '');
//$this->db->where('id', $fileid);
$query = $this->db->get();
if ($query) {
return $query->result();
} else {
return false;
}
}
MODEL WILL update in db where CB=empty
function model2($dados = NULL) {
if ($dados !== NULL) {
// extract($dados);
$this->db->where('CB', '');
$this->db->update('peca', $dados);
return true;
} else {
return false;
}
}
CONTROLLER
$this->load->model('model_peca');
$resultadocadastropeca = $this->model_peca->model1($id);
$data = 'id' => $id;
$appointment = array('codigoean' => $data.'.PECA.');
$appointment = $this->model_peca->model2($appointment);
START TABLE
Previous values inserted from import so CB can only be generated after id exists
id|CB |
22| |
31| |
RESULTS
I'm changing CB to .PECA. in all rows where CB=empty but $id for each row is not passing
id|CB |
22|.PECA.|
31|.PECA.|
EXPECTED
id|CB |
22|22.PECA.|
31|31.PECA.|
I still don't fully understand what you want to do, but if you want to fetch something where a column is empty or null:
$this->db->where("WHERE yourColumn IS NULL OR yourColumn = ''");
As per your revised question, this should work:
$this->db->select('id');
$this->db->where('CB', '');
$q = $this->db->get('peca');
if ($q->num_rows() == 0) {
die('nothing to do here');
}
$res = $q->result();
foreach ($res as $item) {
$data[] = array('id' => $item->id, 'CB' => $item->id . '.PECA.');
}
$this->db->update_batch('peca', $data, 'id');
i am getting error Call to a member function row() on a non-object in codeigniter my controller is
public function edit_survey_pro($id)
{
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (sizeof($survey) == 0) $this->template->error(lang("error_32"));
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
}
my model is
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
{
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
$this->db->limit($perpage,$start);
if($where){
$this->db->where($where);
}
if($order_by){
$this->db->order_by($order_by);
}
if($arr=='')
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
if(!empty($query))
if($perpage != 0 && $perpage != NULL)
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
here loadContent() is just load the content with view path
public function loadContent($view,$data=array(),$die=0){
//something to load the content
}
in my model I am getting the result as an array of object in $query and then it is returned as $result like this -
$query = $this->db->get()->result(); but at the controller $survey stores array of object and i want to show the content of that array of object ,previously I use
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey->row()
)
);
to get that data but the problem is $survey->row() cannot return that data bcoz it is not an object it is array of object so it can't be returned through row() method
so instead of this I just call the first element of that data like this-
$this->template->loadContent("user/edit_survey_pro", array(
"survey" => $survey[0]
)
);
Somehow its works for me bcoz I want to show the first row of the data
if sembody wants to show all data then I think he shuld try logic to increment the key value of that array of object for me it is $survey[] you can use foreach loop for increment the of value of the key element
The problems i see are your model, I will dissect it and add comments to your original code to point out the issues:
function get($table,$where='',$perpage=0,$start=0,$order_by='',$arr='')
//above there are problems, you are setting some of your parameters to
//equal blank, but below, in your conditionals, you are checking if they
// exist. They will always exist if they are set to blank. Fix them by
// setting them = NULL like this:
// get($table,$where=null,$perpage=0,$start=0,$order_by=null,$arr=null)
{
$this->db->select();// <-- you forgot this
$this->db->from($table);
if($perpage != 0 && $perpage != NULL)
//when will $perpage = null? , if never, then you dont need it.
$this->db->limit($perpage,$start);
if($where){
//change this to if(isset($where)). Also why do you use
//curly braces here, but not in the above if statement if only
//one line is affected in your if. I would remove the
//curly braces here.
$this->db->where($where);
}
if($order_by){
// change this to if(isset($order_by)). Same thing as
//above about the curly braces here
$this->db->order_by($order_by);
}
if($arr=='')
// change this to if(isset($arr)).
$query = $this->db->get()->result();
else
$query = $this->db->get()->result('array');
//change this to: $query = $this->db->get()->result_array();
if(!empty($query))
//change the above to if($query->num_rows > 0). Also, here since
//your code body is longer then one line, you will need curly braces
//around your if statement
if($perpage != 0 && $perpage != NULL)
//again, will $perpage ever be NULL? However, why do you need
//this conditional at all, if the limit above is already
//doing this job?
$result = $query;
else
$result = $query[0];
else
$result = array();
return $result;
}
after applying all the changes:
MODEL:
function get($table, $where=null, $perpage=0, $start=0, $order_by=null, $arr=null)
{
$this->db->select();
$this->db->from($table);
if($perpage != 0)
$this->db->limit($perpage, $start);
if(isset($where))
$this->db->where($where);
if(isset($order_by))
$this->db->order_by($order_by);
if(isset($arr)) {
$result = $this->db->get()->result_array();
} else {
$result = $this->db->get()->result();
}
return $result;
}
CONTROLLER
public function edit_survey_pro($id) {
$id = intval($id);
$survey = $this->model->get("surveys",array("ID" => $id),100000);
if (!$survey) {
$this->template->error(lang("error_32"));
} else {
$data["survey"] = $survey;
$this->template->loadContent("user/edit_survey_pro", $data);
}
}
I think when you use $this->db->get(), you need to pass the table name as param like this:
$this->db->get('table_name')->result();
I am calling URL with search params which are dynamic. How could I form proper Eloquent query?
In theory:
query
query where(someParam1)
query where(someParam2)
query orderby(someParam3)
query get
I need this kind of structure so I can use where clause if param exists.
If there is some other way in Laravel, please let me know.
It's easy with Laravel. Just do something like this:
$query = User::query();
if ($this == $that) {
$query = $query->where('this', 'that');
}
if ($this == $another_thing) {
$query = $query->where('this', 'another_thing');
}
if ($this == $yet_another_thing) {
$query = $query->orderBy('this');
}
$results = $query->get();
You can just use the where statement.
For ex: on users table or User model, you want dynamic search on name, id. You can do this
$where = [];
$firstName = $request->get('first_name');
if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
$id = $request->get('id');
if ($id) $where[] = ['id', $id];
$users = User::where($where)->get();
By default, it will return all the users, if anything exists in $where array, it will apply the where condition on that.
You can use like this
$validateUserDetail = User::query();
if (!empty($userDetails['email'])) {
$validateUserDetail->whereemail($userDetails['email']);
}if (!empty($userDetails['cellphone'])) {
$validateUserDetail->wherecellphone($userDetails['cellphone']);
}
$validateUserDetail->select('username');
$validateUserDetail->get()
You can pass dynamic value by below example
$user_auctions = $this->with('userAuctions')
->where('users.id', '=', $id)
->get();
I came here from Google. If you are going to be iterating over more then 5 if statements, its more effective to use a switch statement
if(empty($request->except('_token')))
return 'false';
$models = Vehicle::query();
$request_query = $request->all();
$year_switch = false;
foreach ($request_query as $key => $field_value){
if($field_value != 'any'){
switch($field_value){
case 'X':
case 'Y':
$year_switch = true;
break;
case'Z':
//Dynamic
$models->where($key,'LIKE', $field_value);
break;
}
}
}
You can pass a callback to the where function.
So, you can do something like this:
class TestService {
TestRepository $testeRepository;
public function __construct(TesteRepository $teste) {
$this->testeRepository = $teste;
}
public function getAll(array $filters)
{
$where = function (Builder $query) use ($filters) {
collect($filters)
->each(function ($value, $param) use ($query) {
if ($param === 'test') {
$query->where($param, '=', $value);
} else if ($param === 'test2') {
$query->orWhere($param, '>', $value);
}
});
};
return $this->testRepository->gelAll($where);
}
class TestRepository
{
public function getAll(\Closure $where)
{
$query = TestModel::query();
$query->where($where);
//and put more stuff here, like:
//$query->limit(15)->offset(30)
...
return $query->get();
}
}
And in your controller you pass the filters:
class TestControler ...
{
public function $index()
{
$filters = request()->query();
return $this->testService->getAll($filters);
}
}
I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.