How to get value from Yii2 ActiveQuery array - php

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, e.g. :
$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;

found the solution i added ->one() at the end of query and it works
$data = VehicleRating::find()->where(['vehicle_id' => $id])->one();

Related

How to get the data Using Yii2 Query Builder

What i am trying
I have 2 table staff and salarydetails,i want to fetch staff name and there respective salary
$salaries = SalaryDetails::find()->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$salaries->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$salaries->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
when i try to print sql raw query by using
echo $salaries->createCommand()->getRawsql();
i got SELECT salary_details.total_salary AS salary, staff.name AS name FROM salary_details LEFT JOIN staff ON salary_details.staff_id = staff.id
and this query gives the data i wanted in phpMyadmin
But the array gives ie, print_r($salaries); gives
yii\db\ActiveQuery Object ( [sql] => [on] => [joinWith] => [select] => Array ( [0] => salary_details.total_salary AS salary [1] => staff.name AS name ) [selectOption] => [distinct] => [from] => [groupBy] => [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => staff [2] => salary_details.staff_id = staff.id ) ) [having] => [union] => [params] => Array ( ) [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) [where] => [limit] => [offset] => [orderBy] => [indexBy] => [modelClass] => common\models\SalaryDetails [with] => [asArray] => [multiple] => [primaryModel] => [link] => [via] => [inverseOf] => )
Thanks,
As you can see in your print_r, $salaries is an ActiveQuery instance. Call the methods ->asArray()->all() on it to get the records.
$query = SalaryDetails::find()
->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$query->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$query->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
$salaries = $query->asArray()->all();
Note that without asArray the all would return an array of SalaryDetails records and you would loss the staff name.

How to get the value from a specific key in an array?

I have the following array:
Array (
[result] => Array (
[id] => 58fba3ebf4
[type] => A
[name] => ser.domain.com
[content] => 192.168.100.1
[proxiable] =>
[proxied] =>
[ttl] => 1
[priority] => 10
[locked] =>
[zone_id] => eb0d86828e3ac837c
[zone_name] => domain.com
[modified_on] => 2018-07-06T06:37:14.069598Z
[created_on] => 2018-07-06T06:37:14.069598Z
[meta] => Array (
[auto_added] =>
[managed_by_apps] =>
[managed_by_argo_tunnel] =>
)
)
[success] => 1
[errors] => Array ( )
[messages] => Array ( )
)
How can I just get the value from id?
$data =json_decode($response);
$id = $data->result->id;
Assuming your payload from the request was $response.
You already have a multi-dimensional array so just try like this
echo $arrays['result']['id']; // this will return id
echo $arrays['result']['type']; // this will return type
Here is solution
// $result_array() is your reponse from curl PHP
$data = $result_array();
$id = $data['result']['id'];

How to write Laravel Query in two parts

I am working with Laravel 5.2. I want to write a query in two parts like this:
$getData = DB::table($table)
->where($where);
$getData->first();
return $getData;
But it is not working for me. It Not provides correct data to me.
It gives:
Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Nested [query] => Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Basic [column] => country_name [operator] => = [value] => India [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => ) [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => 1 [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => )
But it works correctly when i call like this:
$getData = DB::table($table)
->where($where)->first();
return $getData;
Can we not call a query in two parts in laravel.
You have to get back the returned data from $getData->first();
$getData = DB::table($table)
->where($where);
$getData = $getData->first(); // <----
return $getData;

PHP Nested Array loop nested results

I am experimenting with my first API and getting stuck with the results. I am getting an Array Back:
Array
(
[GetOrderListResult] => Array
(
[Status] => Success
[MessageCode] => 0
[ResultData] => Array
(
[OrderResponseItem] => Array
(
[0] => Array
(
[NumberOfMatches] => 2
[OrderTimeGMT] => 2014-05-05T03:23:00
[LastUpdateDate] => 2014-05-28T11:41:45.953
[TotalOrderAmount] => 12.7800
[OrderState] => Active
[DateCancelledGMT] =>
[OrderID] => 138711
[ClientOrderIdentifier] => 138711
[SellerOrderID] =>
[OrderStatus] => Array
(
[CheckoutStatus] => NotVisited
[CheckoutDateGMT] => 1900-01-01T00:00:00
[PaymentStatus] => NotSubmitted
[PaymentDateGMT] => 1900-01-01T00:00:00
[ShippingStatus] => Unshipped
[ShippingDateGMT] => 1900-01-01T00:00:00
[OrderRefundStatus] => NoRefunds
)
)
[1] => Array
(
[NumberOfMatches] => 2
[OrderTimeGMT] => 2014-05-05T03:23:00
[LastUpdateDate] => 2014-05-28T12:59:01.78
[TotalOrderAmount] => 6.3900
[OrderState] => Active
[DateCancelledGMT] =>
[OrderID] => 138750
[ClientOrderIdentifier] => 138750
[SellerOrderID] =>
[OrderStatus] => Array
(
[CheckoutStatus] => NotVisited
[CheckoutDateGMT] => 1900-01-01T00:00:00
[PaymentStatus] => NotSubmitted
[PaymentDateGMT] => 1900-01-01T00:00:00
[ShippingStatus] => Unshipped
[ShippingDateGMT] => 1900-01-01T00:00:00
[OrderRefundStatus] => NoRefunds
)
)
)
)
)
)
Now the onyl way I know how to reference a fied such as the order id in the array is:
echo "Order ID: ".$result['GetOrderListResult']['ResultData']['OrderResponseItem']['0']['OrderID'];
But I want to be able to loop through the array of orders and execute code for each item, could somewbody please point me in the right direction for:
a) is there a better way to refernce these fields?
b) how do I loop through the OrderResponseItem part of the array?
The only loop I could think of was for the whole array not nested items in the array.
Sorry if I'm missing something simple....
Thanks and if you need the data in any other format please let me know.
Since you already know the keys you could just use a foreach to access them an point to that key then loop. Something like this:
foreach($result['GetOrderListResult']['ResultData']['OrderResponseItem'] as $value) {
$order_id = $value['OrderID'];
// your other processes
}

Unable to access array element with json_decode

I have used json_decode to get an array from a JSON response:
$result = (json_decode($trends,true));
which gives me the following (I haven't included all of the EstablishmentDetail array results)
Array ( [FHRSEstablishment] => Array ( [Header] => Array ( [#text] => [ExtractDate] => 2012-05-28 [ItemCount] => 5 [ReturnCode] => Success ) [EstablishmentCollection] => Array ( [EstablishmentDetail] => Array ( [0] => Array ( [FHRSID] => 248659 [LocalAuthorityBusinessID] => INS/06/06179 [BusinessName] => Ancient Raj [BusinessType] => Restaurant/Cafe/Canteen [BusinessTypeID] => 1 [AddressLine1] => 26 North Lane, Canterbury, [PostCode] => CT2 7EE [RatingValue] => 3 [RatingKey] => fhrs_3_en-GB [RatingDate] => 2010-11-18 [LocalAuthorityCode] => 180 [LocalAuthorityName] => Canterbury City [Scores] => [SchemeType] => FHRS [Geocode] => )
which I thought I' be able to use a foreach to get to the BusinessName:
foreach ($result->FHRSEstablishment->EstablishmentCollection->EstablishmentDetail as $detail){
echo $detail['BusinessName'];
}
but I'm not getting any results.
The problem is that you're accessing your $result as an object:
$result->FHRSEstablishment
but when you're calling json_decode with the second parameter set to true, it's returning an associative array, which you should access as:
$result['FHRSEstablishment']['EstablishmentCollection'] //...
If you want to be able to access your $result with object notation, you should define it as:
$result = json_decode($trends) //without 2nd parameter = true

Categories