简体   繁体   中英

getting the foreign key in Yii

I have the database like

 ======= Group ========
 id
 name

 ======= Member ========
 id
 group_id
 firstname
 secondname
 membersince

Now in my Group Controller file I have used the action update to update the models

public function actionUpdate($id)
  {
    $model=$this->loadModel($id);
    $member = Member::model()->findByPk($_GET['id']);

    if(isset($_POST['Group']))
    {
      $model->attributes=$_POST['Group'];
      if($model->save())
      {
        $member->attributes = $_POST['Member'];
        $member->group_id = $model->id;
        if($member->save())
        {
          $this->redirect(array('view','id'=>$model->id));
        }
      }
      $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
      'model'=>$model,
      'member'=>$member,
    ));
  }

Now as I have two model Group and Member , and in group controller file I am saving member attributes. So my problem is when I am using this line $member = Member::model()->findByPk($_GET['id']); for getting the group_id from table member where I can get the complete fields for the group. So can some one tell me how o get the group_id from that table.I searched the documntationbut not got any field like findByFk. So pls guide me.

The relation between is Group and Member is ONE to MANY, so more than one member could exist for a single group id, and your action behavior doesn't look completely correct.

Anyway, the code you are looking for should be the following:

$member = Member::model()->findByAttributes(array('group_id', $_GET['id']));

It is documented here: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findByAttributes-detail

您可以使用findByAttributes()

$member = Member::model()->findByAttributes(array('group_id'=>$_GET['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