0

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,

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.