Group By cause non object - mysql

I'm using codeigniter and I'm trying to perform a query execution passing a where clause, this where is an array, this is my code:
$now = date('Y-m-d H:i:s');
$this->record_model->getAllRecord(array('guid' => $guid,
'end_datetime <' => $now,
'GROUP BY hash'));
this is the content of getAllRecord
$query = $this->db
->select('*')
->from('appointments')
->where($where_clause) 'is passed as parameter..
->get()->result_array();
this is the content of where
array(3) {
["guid"]=>
string(36) "c3682d6f-75b2-4686-966d-cb3c9344369b"
["end_datetime <"]=>
string(19) "2016-01-21 12:03:58"
[0]=>
string(13) "GROUP BY hash"
}
Now if I remove the Group by all working well, but if I insert the Group By hash for don't have (duplicate) in the result this error appear:
Call to a member function result_array() on a non-object
Essentially I want get the information of all records but some records have the same hash, so the GROUP BY should join this record in one. But I did something wrong...

Group by is not part of the where clause, therefore codeigniter will generate a syntactically incorrect code, therefore ->get() call does generate a proper resultset. You should add the group by clause using a separate ->group_by(...) call to your query.

Try this
$query = $this->db->select('*')
->where($where_clause)
->get('appointments');
$result = $query->result_array();
return $result;

Related

Why 'where' return all data in laravel

I am applying search filter in my project so first of all I get data from multiple tables and store in two different variables and then merge these two variable into one so I can filter data from that merged variable. So my code is like that
$data1=Model::query()
->Join('...')
->leftJoin('...')
->where('id',login_user)
->select(...)
->whereRaw('id IN (select MAX(id) FROM table GROUP BY name)')
->groupBy('name')
->get();
$data2=Model2::query()
->leftJoin(...)
->select(...)
->where('id',login_user)
->whereNotIn(..)
->get();
both data1 and data2 return same column with different values so I merge both variable like that
$results = $data1->concat($data2);
No when I already get data so now I need to add filter data from $results so i make post method for that .
so When user request to filter data with name I write query like that
if ($request->name!="") {
$results->when(request('name'), function($q){
$q->Where('name', request('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
But that query is not filtering the data and return me all data.I am new in laravel so I don't know what I have done wrong in that any favour will be helpful for me ,thanks.
if (request()->has('name')) {
$results->when(request()->get('name'), function($q){
return $q->where('name', request()->get('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
As you use 'when()', you can drop the if expression all together:
$results->when(request()->has('name'), function($q){
return $q->where('name', request()->get('name'));
});
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
request() is a Laravel helper for Request $request
Edit: the where() clause in the ORM is with a small 'w', not 'W' as in orWhere

Yii2 Matching all values in IN clause

Im trying to get a query which matches all values within an IN clause. This is what I have right now in UsersSearch.php model:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->column();
$query->andWhere(['userID'=>$categoryIdsMatching]);
But it gets records matching at least one of the values... How can I set that andWhere clause to match all values instead of some of them?
This could be something similiar to:
$categoryIdsMatching = UsersCategoriesAssn::find()
->select('userID')
->distinct(true)
->joinWith('userCategory')
->andWhere(['IN', 'usersCategories.id', $this->catNameSearch])
->groupBy('userTable.userID')
->having('COUNT(userTable.userID) ='.count($this->catNameSearch));
There is propably no other way to filter IN operator to match all values in MySQL.
Yii2 where in clause
Model :
//GET MULTIPLE AREA
public function getAreaSelected() {
//GET SAVE COMMA SEPERARED VALUE CONVERT IN TO ARRAY
$areaArray = explode(",", $this->attributes['selected_area']);
$query = AreaMaster::find()->where(['IN', 'id', $areaArray])->all();
return $query; //$this->hasMany(AreaMaster::className(), ['IN', 'id', $pks]);
}
VIEW FILE :
<?php
print '<pre>';
print_r($model->areaSelected);
exit;
?>

Codeigniter - How to get records from database where one fields value is more than another?

In my database I have two columns named 'amount_raised' and 'funding_goal'.
I would like to get all records from my database where the 'amount_raised' is equal to or more than the 'funding_goal'.
I am using Codeigniters active record. This is what I have so far:
function get_recently_successful($limit, $offset){
$data = '';
$this->db->order_by('date','desc');
$this->db->where('published', '1');
$this->db->where('amount_raised >=', 'funding_goal');
$query = $this->db->limit($limit, $offset)->get('projects');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date,
'project_title' => $row->project_title,
);
}
return $data;
}
The code above just returns all values in the database. Not how I specified it with where. How can I make it work??
Try this instead.
$this->db->where('amount_raised >= funding_goal');
Right now you send the value 'funding_goal' through the query, thus making it:
WHERE amount_raised >= 'funding_goal'
You want it compare with a column and not a string:
WHERE amount_raised >= funding_goal
You can always troubleshoot your query by inserting:
echo $this->db->last_query();
After the $query = row.
If you are using multiple condition in array, you can try the below as well:
$this->db->where(array('status' => 'Active', 'category' => $catId));
You can use another condition as well like this:
$this->db->where('amount_raised >= funding_goal');
You can use the last_query() to see the sql query as well to understand it.

What is wrong with this Code Igniter mySQL query?

I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)

"No result was found for query although at least one row was expected." Query should display records though in Symfony

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:
$em = $this->getDoctrine()->getEntityManager();
$repository = $this->getDoctrine()
->getRepository('ShoutMainBundle:Content');
$query = $repository->createQueryBuilder('p')
->where('p.slug > :slug')
->andWhere('p.subtocontentid > :parent')
->setParameters(array(
'slug' => $slug,
'parent' => $page
))
->getQuery();
$content = $query->getSingleResult();
However, when this code is executed it returns the following error:
No result was found for query although at least one row was expected.
I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.
Have I missed something?
As it was answered here
You are getting this error because you are using the
getSingleResult() method. it generates an Exception if it can't find
even a single result. you can use the getOneOrNullResult() instead
to get a NULL if there isn't any result from the query.
Query#getSingleResult(): Retrieves a single object. If the result
contains more than one object, an NonUniqueResultException is thrown.
If the result contains no objects, an NoResultException is thrown. The
pure/mixed distinction does not apply.
No result was found for query although at least one row was expected.
Another reason could be:
You did this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
return $query->getSingleResult();
Instead of this
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM MyBundle:User u
WHERE u.email = :email')
->setParameter('email', $email);
$query->setMaxResults(1);
return $query->getResult();
Don't you want to use "=" instead of ">" ?
If you've got this message because used
$content = $query->getSingleResult();
you can just replace it with the row below
$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;