How to get the data Using Yii2 Query Builder - php

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.

Related

WordPress - Order by ACF date, date first, then empty fields last

I'm trying to order content by the dick picker provided by ACF.
order by date field
Dates in order of soonest(past/present) to farthest out (ASC ordering).
Then any post that meets the criteria but doesn't have a date set would be last.
I have the following Query arguments:
(
[post_type] => people
[posts_per_page] => 10
[paged] => 1
[meta_query] => Array
(
[0] => Array
(
[key] => has_scheduling
[value] => 1
)
[1] => Array
(
[key] => custom_ID
[compare] => !=
[value] =>
)
[2] => Array
(
[key] => date_picker
[compare] => !=
[value] =>
)
)
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => people_types
[field] => term_id
[terms] => 153
)
)
[meta_key] => date_picker
[orderby] => meta_value_num
[order] => ASC
)
I noticed that this Query will only load the first part correctly. It grabs content based on all the parameters, then orders is by date, but it excludes the content that doesn't have a date set.
I've tried this as well:
(
[post_type] => people
[posts_per_page] => 10
[paged] => 1
[meta_query] => Array
(
[0] => Array
(
[key] => has_scheduling
[value] => 1
)
[1] => Array
(
[key] => custom_ID
[compare] => !=
[value] =>
)
[2] => Array
(
[relation] => OR
[0] => Array
(
[key] => date_picker
[compare] => EXISTS
)
[1] => Array
(
[key] => date_picker
[compare] => NOT EXISTS
)
)
)
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => people_types
[field] => term_id
[terms] => 153
)
)
[orderby] => meta_value
[order] => ASC
)
So here I don't exclude empty fields, I check if it exists and then doesn't. Then order by the data again. I also switched to use meta_value instead of meta_value_num
Any tips or tricks, or if you have run into issue as well, I'd love to see what you did.
For anyone also trying to do the same, the end result for this ended using a custom a orderby filter. Example code below.
// Order By custom date.
add_filter('posts_orderby', function (string $orderby, WP_Query $query) {
if ($query->get('orderby') === '__custom_date__') {
$orderby = "mta.meta_value is NULL, mta.meta_value ='', mta.meta_value ASC";
}
return $orderby;
}, 10, 2);
// Extra join to order by custom date.
add_filter('posts_join', function (string $join, WP_Query $query) {
if ($query->get('orderby') === '__custom_date__') {
$join .= " LEFT JOIN wp_postmeta AS mta ON ( wp_posts.ID = mta.post_id AND mta.meta_key = 'date_picker')";
}
return $join;
}, 10, 2);
This is then used as a parameter that gets passed to orderby
$args['orderby'] = '__custom_date__';

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;

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, 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();

Drupal - Unable to get result from db_query

I have written below code in drupal module.
echo '<pre>';
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
print_r($data);
die;
But it is not giving me users data it is giving me below output:
DatabaseStatementBase Object
(
[dbh] => DatabaseConnection_mysql Object
(
[needsCleanup:protected] =>
[target:protected] => default
[key:protected] => default
[logger:protected] =>
[transactionLayers:protected] => Array
(
)
[driverClasses:protected] => Array
(
[SelectQuery] => SelectQuery
)
[statementClass:protected] => DatabaseStatementBase
[transactionSupport:protected] => 1
[transactionalDDLSupport:protected] =>
[temporaryNameIndex:protected] => 0
[connectionOptions:protected] => Array
(
[database] => aaldev
[username] => root
[password] =>
[host] => localhost
[port] =>
[driver] => mysql
[prefix] => Array
(
[default] =>
)
)
[schema:protected] =>
[prefixes:protected] => Array
(
[default] =>
)
[prefixSearch:protected] => Array
(
[0] => {
[1] => }
)
[prefixReplace:protected] => Array
(
[0] =>
[1] =>
)
)
[queryString] => SELECT uid, name, status, created, access FROM users u WHERE uid <> 0 LIMIT 50 OFFSET 0
)
Please help me on this.
Assuming that your query is correct, and Drupal documentation, you have a fetchAll() method:
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
$data->fetchAll();
Retrieve all records into an indexed array of stdClass objects.

Echo return values from rows from db

Does it make difference to get the value of result set when using alias names and join in the SQL generated using zend framwork.
Regarding to the sql resulted from the selected answer in this question I want to print all result in .phtml file.
I make like this
<?php
foreach($this->rows as $row){
echo $row->visit_id . ' ' . $row->rep_id . ' '.$row->target;
?>
When I print the size of $this->rows it returns the correct number of rows, but it doesn't print any thing?!
Edit
here's what I get when I print $rows
Zend_Db_Statement_Pdo Object ( [_fetchMode:protected] => 2 [_stmt:protected] => PDOStatement Object ( [queryString] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object ( [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array ( [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] => 0 [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] => 2 [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2 [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo [_config:protected] => Array ( [dbname] => inspection [username] => root [password] => 123456 [charset] => [persistent] => [options] => Array ( [caseFolding] => 0 [autoQuoteIdentifiers] => 1 [fetchMode] => 2 ) [driver_options] => Array ( ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object ( [_queryProfiles:protected] => Array ( ) [_enabled:protected] => [_filterElapsedSecs:protected] => [_filterTypes:protected] => ) [_defaultProfilerClass:protected] => Zend_Db_Profiler [_connection:protected] => PDO Object ( ) [_caseFolding:protected] => 0 [_autoQuoteIdentifiers:protected] => 1 [_allowSerialization:protected] => 1 [_autoReconnectOnUnserialize:protected] => ) [_attribute:protected] => Array ( ) [_bindColumn:protected] => Array ( ) [_bindParam:protected] => Array ( ) [_sqlSplit:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_sqlParam:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_queryId:protected] => )
If you are using the query you accepted in the other question, your field names should be as you expect.
I usually just var_dump $row to see what's there is what I expect:
<?php
foreach($this->rows as $row){
//Zend_Debug::dump() provides formatted debug info, the second argument is a label
Zend_Debug::dump($row, 'Row')
?>
This should give you a pretty good idea of what each row contains with out all the baggage that $rows has.
Heh, and that's why I pointed You to ReferenceMap i Zend_Db_Tables. Check my answer to Your previous question.
https://stackoverflow.com/a/9905206/1278879
Using my code from Your previous question You could've done it like this:
foreach ($reportRowset as $reportRow) {
echo $reportRow->visit_id . ' ' . $reportRow->rep_id . ' '.$visitRow->target;
}
And that's piece of cake
The row is not an object, its an array and it can be get like this:
print $row['rep_id']

Categories