简体   繁体   中英

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'guidian.id' in 'where clause' in yii2

I am new to Yii2 PHP framework, I have student form to get student details and guardian id_no and on submission I get this error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'guidian.id' in 'where clause' The SQL being executed was: SELECT EXISTS(SELECT * FROM guidian WHERE guidian.id='123') The student table has guidian_id as a foreign key referencing id_no on guidian table, I am confused with error to say guidian.id while actually no where I specified an id as a column in guidian table(I don't have id column in guidian table). Note: I understand the typo guidian instead of guardian

Here is ManageStudentController.php

<?php

namespace app\controllers;

use app\models\District;
use app\models\Subclass;
use app\models\Studentclass;
use app\models\Guidian;
use Yii;
use app\models\Student;
use app\models\StudentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use  yii\web\Session;

/**
 * ManageStudentController implements the CRUD actions for Student model.
 */
class ManageStudentController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout','index','view','create','update','delete','district-list'],
                'rules' => [
                    [
                        'actions' => ['logout','index','view','create','update','delete','district-list'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['GET','POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Student models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new StudentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**
     * Displays a single Student model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Student model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Student();
        // die(var_dump($model->first_name));
        // die(var_dump(Yii::$app->request->post()));
        if ($model->load(Yii::$app->request->post())) {
            $Studentclass = new Studentclass();
            $Studentclass->class_id = $model->class_id;
            $Studentclass->subClass_id = $model->subClass_id;
            $Studentclass->student_id = $model->adm_no;
                //die(var_dump($model->subClass_id));

                if(!$model->control_field){//this guidian is not existing in db
                    //var_dump($model);exit();
                    $modelGuidian = new Guidian();
                    
                    $modelGuidian->id_no = $model->guidian_id;
                    $modelGuidian->id_type = $model->id_type;
                    if($modelGuidian->save()){
                        $model->save();
                        $Studentclass->save();
                        return $this->redirect(array('guidian/create?guidian_id='.$modelGuidian->id_no));
                    }                   
                }else{
                    $model->save();
                    $Studentclass->save();
                }
                      
        }

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

    public function actionCheckGuidian(){
        $model = new Guidian();
        $searchParams = Yii::$app->request->get();
        
            if($searchParams["id_type"] && $searchParams["guidian_id"]) {
                 $model = Guidian::find()->where(['id_type'=>$searchParams["id_type"], 'id_no'=>$searchParams["guidian_id"]])->one()??$model;

                 $flag = $model ->isNewRecord?'0':'1';
            }
        
            echo $flag;
    }
    /**Getting the list of districts based to the selected region
     * passed region Id as parameter
     */
    public function actionDistrictList($district){
        $districtList = District::findBySql('select * from district where region_id ="'.$district.'"')->all();
        //return $districtList;
        if(count($districtList) > 0){
            foreach($districtList as $value){
                echo "<option value = '".$value->id."'>".$value->name."</option>";
            }
        }else{
            echo "<option>...</option>";
        }
    }

    /**Getting the list of sub-classes based to the selected class
     * passed class Id as parameter
     */

    public function actionClassList($class_id){
        $subclassList = Subclass::findBySql('select * from subclass where class_id ="'.$class_id.'"')->all();
        //return $districtList;
        if(count($subclassList) > 0){
            foreach($subclassList as $value){
                echo "<option value = '".$value->id."'>".$value->name."</option>";
            }
        }else{
            echo "<option>...</option>";
        }
    }

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

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('flash', 'Remove');
            return $this->redirect(['view', 'id' => $model->adm_no]);
        }

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

    /**
     * Deletes an existing Student model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        Yii::$app->session->setFlash('flash', 'Remove');
        return $this->redirect(['index']);
    }

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

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

And here is model the Student.php

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "student".
 *
 * @property int $adm_no
 * @property string|null $first_name
 * @property string|null $middle_name
 * @property string|null $last_name
 * @property string|null $gender
 * @property string|null $date_of_birth
 * @property int|null $guidian_id
 * @property string|null $guidian_relation
 * @property int|null $home_region_id
 * @property int|null $home_district_id
 * @property int|null $status
 *
 * @property Payment[] $payments
 * @property District $homeDistrict
 * @property Guidian $guidian
 * @property Region $homeRegion
 * @property Studentclass[] $studentclasses
 */
class Student extends \yii\db\ActiveRecord
{
    public $id_type;
    public $class_id;
    public $subClass_id;
    public $control_field;
    // public $id_no;
    public $date_joined;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'student';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['date_of_birth','guidian_id','control_field','date_joined'], 'safe'],
            [['home_region_id', 'home_district_id', 'status','class_id','subClass_id'], 'integer'],
            [['first_name', 'middle_name', 'last_name'], 'string', 'max' => 100],
            [['gender'], 'string', 'max' => 6],
            [['guidian_relation'], 'string', 'max' => 255],
            [['home_district_id'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['home_district_id' => 'id']],
            [['guidian_id'], 'exist', 'skipOnError' => true, 'targetClass' => Guidian::className(), 'targetAttribute' => ['guidian_id' => 'id']],
            [['home_region_id'], 'exist', 'skipOnError' => true, 'targetClass' => Region::className(), 'targetAttribute' => ['home_region_id' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'adm_no' => yii::t('app','Admission No:'),
            'first_name' => yii::t('app','First Name:'),
            'middle_name' => yii::t('app','Middle Name:'),
            'last_name' => yii::t('app','Last Name:'),
            'gender' => yii::t('app','Gender:'),
            'date_of_birth' => yii::t('app',''),//label text is on view page
            'guidian_id' => yii::t('app','Guidian Id number:'),
            'guidian_relation' => yii::t('app','Guidian Relation:'),
            'home_region_id' => yii::t('app','Home Region:'),
            'home_district_id' => yii::t('app','Home District:'),
            'status' => yii::t('app','Status:'),
            'id_type' => yii::t('app','Guidian ID Type:'),
            'class_id' => yii::t('app','Class:'),
            'subClass_id' => yii::t('app','Sub Class:'),
            'date_joined' => yii::t('app',''),
        ];
    }

    /**
     * Gets query for [[Payments]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getPayments()
    {
        return $this->hasMany(Payment::className(), ['student_id' => 'adm_no']);
    }

    /**
     * Gets query for [[HomeDistrict]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getHomeDistrict()
    {
        return $this->hasOne(District::className(), ['id' => 'home_district_id']);
    }

    /**
     * Gets query for [[Guidian]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getGuidian()
    {
        return $this->hasOne(Guidian::className(), ['id_no' => 'guidian_id']);
    }

    /**
     * Gets query for [[HomeRegion]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getHomeRegion()
    {
        return $this->hasOne(Region::className(), ['id' => 'home_region_id']);
    }

    /**
     * Gets query for [[Studentclasses]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getStudentclasses()
    {
        return $this->hasMany(Studentclass::className(), ['student_id' => 'adm_no']);
    }
}

and here is guardian model guidian.php

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "guidian".
 *
 * @property string $id_no
 * @property string|null $id_type
 * @property string|null $first_name
 * @property string|null $middle_name
 * @property string|null $last_name
 * @property int|null $region_of_residence
 * @property int|null $district_of_residence
 * @property string|null $primary_contact
 * @property string|null $other_contact
 * @property string|null $email
 *
 * @property District $district
 * @property Region $region
 * @property Student[] $students
 */
class Guidian extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'guidian';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id_no'], 'required'],
            [['region_of_residence', 'district_of_residence'], 'integer'],
            [['id_no', 'id_type'], 'string', 'max' => 50],
            [['first_name', 'middle_name', 'last_name'], 'string', 'max' => 100],
            [['primary_contact', 'other_contact', 'email'], 'string', 'max' => 255],
            [['id_no'], 'unique'],
            [['district_of_residence'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['district_of_residence' => 'id']],
            [['region_of_residence'], 'exist', 'skipOnError' => true, 'targetClass' => Region::className(), 'targetAttribute' => ['region_of_residence' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id_no' => Yii::t('app','Guidian Id Number:'),
            'id_type' => Yii::t('app','Guidian Id Type:'),
            'first_name' => Yii::t('app','First Name:'),
            'middle_name' => Yii::t('app','Middle Name:'),
            'last_name' => Yii::t('app','Last Name:'),
            'region_of_residence' => Yii::t('app','Region Of Residence:'),
            'district_of_residence' => Yii::t('app','District Of Residence:'),
            'primary_contact' => Yii::t('app','Primary Contact:'),
            'other_contact' => Yii::t('app','Other Contact:'),
            'email' => Yii::t('app','Email:'),
        ];
    }

    /**
     * Gets query for [[District]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getDistrict()
    {
        return $this->hasOne(District::className(), ['id' => 'district_of_residence']);
    }

    /**
     * Gets query for [[Region]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getRegion()
    {
        return $this->hasOne(Region::className(), ['id' => 'region_of_residence']);
    }

    /**
     * Gets query for [[Students]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getStudents()
    {
        return $this->hasMany(Student::className(), ['guidian_id' => 'id_no']);
    }
}

抱歉,我已经解决了,规则函数中有一个 Id 关联了两个表

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