A
A
Alexey-V2020-07-02 20:29:44
Yii
Alexey-V, 2020-07-02 20:29:44

Yii2 Invalid argument supplied for foreach() what is the meaning of the error?

I know a similar question has already been asked. But the questioner's code is more complicated, what nonsense I have, and earlier this approach worked:

here is the model:
<?php

namespace app\models;

use yii\db\ActiveRecord;

class Master extends ActiveRecord {

}

controller:
<?php

namespace app\controllers;

use yii\web\Controller;
use yii\data\Pagination;
use app\models\Master;

class MasterController extends Controller {
public function actionRost() {
$masters = Master::find()->select('id' => '1')->where('rost')->one();
return $this->render('index', compact('masters'));
}
}

the view is more precisely the place where the cycle is located:
<?php foreach ($masters as $master): ?>

<?=$master->rost?>

<?php endforeach; ?>

Everything seems very simple, but this time it gives an error

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2020-07-02
@Alexey-V

This query does not return an array. It's either empty or not an array.

$masters = Master::find()->select('id' => '1')->where('rost')->one();

Accordingly, foreach (array search) is not required in the code. Take it away!

S
smigles, 2020-07-02
@smigles

$masters = Master::find()->select('id' => '1')->where('rost')->one();
What does this design mean?
If you need one record where the primary key id is 1, then you need to write like this:
$master = Master::findOne(1);

<?= $master->rost ?>

If you want all records where rost is 1, then like this:
$masters = Master::findAll(['rost' => 1]);

<?php foreach ($masters as $master): ?>
    <?= $master->rost ?>
<?php endforeach ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question