简体   繁体   中英

How to get value from Yii2 ActiveQuery array

I have a table containing fields

id, vehicle_id, vehicle_rating_type, vehicle_rating, rating_time

I want to get values based in vehicle_id , so I fired query

$id = Yii::$app->getRequest()->getQueryParam('id');
$data = VehicleRating::find()->where(['vehicle_id' => $id]);

Now when I prints $data array in view file using print_r function I get following result.

yii\db\ActiveQuery Object ( 
    [sql] => 
    [on] => 
    [joinWith] => 
    [select] => 
    [selectOption] => 
    [distinct] => 
    [from] => 
    [groupBy] => 
    [join] => 
    [having] => 
    [union] => 
    [params] => Array ( ) 
    [_events:yii\base\Component:private] => Array ( ) 
    [_behaviors:yii\base\Component:private] => Array ( ) 
    [where] => Array ( 
        [vehicle_id] => 1 
    ) 
    [limit] => 
    [offset] => 
    [orderBy] => 
    [indexBy] => 
    [modelClass] => backend\models\VehicleRating 
    [with] => 
    [asArray] => 
    [multiple] => 
    [primaryModel] => 
    [link] => 
    [via] => 
    [inverseOf] => 
)

How to retrive values from this array to show in view file? Say I want to say vehicle_id and vehicle_rating . How to print it?

You should simply execute the query, eg :

$rating = VehicleRating::find()->where(['vehicle_id' => $id])->one();
echo $rating->vehicle_rating;

Or if you want array instead of object :

$rating = VehicleRating::find()->where(['vehicle_id' => $id])->asArray()->one();
echo $rating['vehicle_rating'];

Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data

Use query params .

$vehicleRatingQuery = VehicleRating::find()->where('vehicle_id = :vehicleId', [
    ':vehicleId' => $id
]);

$vehicleRatingQueryParams = $vehicleRatingQuery->params;

找到了我在查询末尾添加的解决方案-> one(),并且有效

$data = VehicleRating::find()->where(['vehicle_id' => $id])->one();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM