简体   繁体   English

如何从Yii2 ActiveQuery数组中获取价值

[英]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 我想获取基于vehicle_id值,所以我触发了查询

$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. 现在,当我使用print_r函数在视图文件中打印$data数组时,得到以下结果。

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 . 说我想说vehicle_idvehicle_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 : 或者,如果您想要数组而不是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 阅读更多: 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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