I want to get all rows , certain columns using CActive record
I heard about findAll(); but it returns all rows, colums
$models = Users::model()->findAll();
How to get certain columns for example, only username, password for all users?
You can do with CDbCriteria
$criteria = new CDbCriteria;
$criteria->select = 't.username, t.password '; // select fields which you want in output
$models = Users::model()->findAll($criteria);
If you want the result in the form of array try this
$records= Yii::app()->db->createCommand()
->select('username,password')
->from('users')
->queryAll();
If as an object then kumar_v has already given an answer
the Kumar_v 's answer is completely correct, but if you want only username and password (or any two fields),
you can also use CHtml::listData() function like this :
$users=CHtml::listData(Users::model()->findAll(array('condition'=>'*condition*',
'limit'='*limit*')),"username", "password");
the $users is an array like this :
$users = array(
'username1'=>'password1',
'username2'=>'password2',
.
.
.
);
and of course you can access to a username's password simply by $users['username1']
You could use as usual sql query but getting so would not be in yii standard
So get findAll() and get the data that you want. that is proposed and best.
Related
I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();
I'm trying to personalize a symfony 2.4 repository query to retrieve only some fields. Everything is ok with flat fields but when retrieving Entity fields, I only get the id (by default) but not the whole entity data. My query:
$select = $this->createQueryBuilder('ca')
->select('ca.id, ca.name')
->leftJoin('ca.users', 'user')
->addSelect('(user) as users');
$select->setMaxResults($count);
return $select->getQuery()->getResult();
The result is: [{id: 1, name: "Some name", users: 1}, ...]
How can I change this query for users to contain the whole user data, like id, name, address, etc.?
This works for me:
$select = $this->createQueryBuilder('ca')
->select('partial ca.{id, name}, users')
->leftJoin('ca.users', 'users');
$select->setMaxResults($count);
return $select->getQuery()->getArrayResult();
You should try this way. You can use Partial.
$select = $this->createQueryBuilder('ca')
->select('partial ca.{id, name}')
->leftJoin('ca.users', 'users')
->addSelect('users');
A detailed description of this issue is available here. Doctrine2: Cannot select entity through identification variables without choosing at least one root entity alias
change this:
->select('ca.id, ca.name')
to this:
->select('ca')
i hope this will useful for you.
$qb = $this->em->createQueryBuilder();
$qb->select('o.id as order_id,o.createdBy as created_by,o.user as user_id');
// for getting selective fields
//$qb->select('o');
//for getting all fields in certain table
$qb->from('Entity\Orders', 'o');
$qb->setMaxResults(1);
// for getting single record only.
return $qb->getQuery()->getOneOrNullResult();
// for getting single record or null record.
//return $qb->getQuery()->getResult();
// for getting multiple records.
feel free to ask any query regarding it.
How to select certain columns on parents table while querying with eager loading?
$accounts = \App\Account::with('status')->get();
Return
[{"id":1,"username":"kuhn.desiree","email":"quentin.gleason#example.net","last_login":"2009-04-02 23:21:20","created_at":"2017-07-15 19:07:03","updated_at":"2017-07-15 19:07:03","status_id":13,"status":{"id":13,"name":"ab","desc":"Quos quas.","created_at":"2017-07-15 19:07:01","updated_at":"2017-07-15 19:07:01"}}]
I only want username and email on Account table.
Try to use this code:
$accounts = \App\Account::with(['status' => function($q)
{
$q->select('username', 'email');
}])->get();
one way is using select() method
$accounts = \App\Account::with('status')->select('username', 'email','status_id')->get();
If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method.:
accounts = \App\Account::with('status')->pluck('username', 'email');
You want to add a select call:
$accounts = \App\Account::with('status')->select('username', 'email')->get();
How to run 'OR' condition in model()->findByAttributes()?
This is my code:
$criteria->condition='url_title_en=:x OR url_title_da=:x';
$criteria->params=array(':x'=>$_GET['purl_title']);
$parentcat = Category::model()->findByAttributes($criteria);
But I'm getting this error:
Table "tbl_category" does not have a column named "select".
You can use OR like this
$criteria=new CDbCriteria();
$criteria->select='category_id';
$criteria->condition='url_title_en=:x';
$criteria->addCondition('url_title_da=:x','OR');
$criteria->params=array(':x'=>$_GET['purl_title']);
In above code addCondition appends the extra condition with OR operator. Now If you expect multiple records then you can use
$parentcat = Category::model()->findAll($criteria);
If you expect single record the you can use
$parentcat = Category::model()->find($criteria);
What you are using here that you are passing criteria to function FindByAttributes() which finds records with respect to attributes passed to it. Now you are passing it criteria and it finds first word as "select" because criteria translates your query like "select * where category_id=3". Now findByAttributes() take it as an attribute and tries to find it. thats why it shows error that tble_category cant find select.Here is official documentation of yii http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAll-detail
The only problem with your code was that you were using findByAttributes instead of findAll.
$criteria = new CDbCriteria;
$criteria->condition = '`url_title_en` = :uri OR `url_title_da` = :uri';
$criteria->params = array(':uri' => $_GET['purl_title']);
$records = Category::model()->findAll($criteria);
// print all records fetched.
print_r($records);
I have an array of Ids which has already been ordered based on some criterias
Example:
$array = array(5,4,10,3,1);
and i am using yii to get all these records from database:
$records = TableName::model()->findAllByPk($array);
this is returning me the correct results but its being sorted by the primary key in ascending order.
i even tried using CDbCriteria like this:
$criteria = new CDbCriteria();
$criteria->addInCondition('primaryKeyColumnName',$array);
$records = TableName::model()->findAll($criteria);
and its still being sorted.. can anyone help me plz
Add This line and try I think It will work as you want.
$criteria->order = "FIELD(id, '5,4,10,3,1')";