简体   繁体   中英

Yii2 query result always returns the same

I am working on a Yii2 based project right now. Today when I was testing my application I noticed a very interesting bug in it. I have a Products table with it's model and controllers and views. (These are generated with gii) When I list all the records in the index action it works fine. But here comes the bug. When I click on the edit or view action it alwasy renders the first record in the database. I was var_dump the result of the queries and always returnd the mentiond result. Only when I used createCommand got the proper result.

What do you think guys could be the problem with it?

The controller

<?php

namespace backend\controllers;

use Yii;
use app\models\Termek;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * TermekController implements the CRUD actions for Termek model.
 */
class TermekController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Termek models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Termek::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Termek model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new Termek model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Termek();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Termek model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Termek model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Termek model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Termek the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Termek::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

The index.php view file

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Termeks');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="termek-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Create Termek'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'nev',
            'szelesseg',
            'magassag',
            'egyeb:ntext',
            // 'ar',
            // 'termek_kategoria_id',
            // 'torolt',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

Part of view.php view file:

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'nev',
            'szelesseg',
            'magassag',
            'egyeb:ntext',
            'ar',
            'termek_kategoria_id',
            'torolt',
        ],
    ]) ?>

Model file:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "termek".
 *
 * @property integer $id
 * @property string $nev
 * @property double $szelesseg
 * @property double $magassag
 * @property string $egyeb
 * @property string $ar
 * @property integer $termek_kategoria_id
 * @property string $torolt
 */
class Termek extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'termek';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nev', 'termek_kategoria_id'], 'required'],
            [['szelesseg', 'magassag'], 'number'],
            [['egyeb'], 'string'],
            [['ar', 'termek_kategoria_id'], 'integer'],
            [['torolt'], 'safe'],
            [['nev'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'nev' => Yii::t('app', 'Nev'),
            'szelesseg' => Yii::t('app', 'Szelesseg'),
            'magassag' => Yii::t('app', 'Magassag'),
            'egyeb' => Yii::t('app', 'Egyeb'),
            'ar' => Yii::t('app', 'Ar'),
            'termek_kategoria_id' => Yii::t('app', 'Termek Kategoria ID'),
            'torolt' => Yii::t('app', 'Torolt'),
        ];
    }

    /**
     * @inheritdoc
     * @return \app\models\Query\TermekQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\models\Query\TermekQuery(get_called_class());
    }
}

Try modify the findModel function using find()->where instead of findOne

protected function findModel($id)
{
    var_dump($id);
    $model = Termek::find()->where(['id'=> $id])->one();
     var_dump($model);
    if (($model !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

I am not sure why but somehow the error solved. I had a function in TermekQuery that was supposed to query all the records that has the deleted field null. I removed it and now works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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