Reputation: 956
I want to get a specific column from User table in yii2 using active record below is my code
$model = User::findOne(['id' => 1]);
this will return all the column from the table with user id equal 1, but suppose i just want to get only username and email from this column how do i write the query with active record, i tried the below code but it wont work..`
$model = User::find('username','email')->where('id'=1)
Upvotes: 15
Views: 49635
Reputation: 569
If you need Model User, try this:
$user = User::find()
->select('column1, column2')
->where(['id' => $id])
->one();
For getting few columns without Model use this:
$columns = User::find()
->select('column1, column2')
->where(['id' => $id])
->asArray()
->one();
If you need single column without Model, use this:
$column = User::find()
->select('column1')
->where(['id' => $id])
->column();
OR
$column = User::find()
->select('column1')
->where(['id' => $id])
->scalar();
Upvotes: 3
Reputation: 153
Below way is correct. but other filed values are returning as NULL.
$model = User::find()->select(['username','email'])->where('id=1')->One();
The best way is to use the cdbcriteria for the Query.
Upvotes: 0
Reputation: 9652
Try this:
$model = User::find()
->select('column1, column2')
->where(['id' => $id])
->one();
echo $model->column1;
Upvotes: 24
Reputation: 186
$model = User::find()
->select(['column1', 'column2'])
->where(['id' => $id])
->one();
Upvotes: 1
Reputation: 5456
Simply try:
$model = User::find()->select(['username','email'])->where('id=1')->One();
OR
$model = User::find()->select(['username','email'])->where('id=:id', [ ':id' => 1 ])->One();
Second way is more preferable.
Upvotes: 3