Stephen
Stephen

Reputation: 2540

difference between $model->foo and FindbyPK - yii

I'm trying to understand the difference between calling variable within a model and also trying to find a specific dataset in a datatable. In my actionCreate I have

public function actionCreate($id)
{
    $model=new Recipient;
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Recipient']))
    {
        $model->attributes=$_POST['Recipient'];
        if($model->save())
        {
            Recipient::model()->updateListId($id, $model);
            $this->redirect(array('view','id'=>$model->id));
        }
    }

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

and in my model I've tried to do this

public function updateListId($id, $model)
{
    $model->list_id = $id;
    echo $id;
}

Why doesn't my model update like so? Should I be using findByPK?


Update

When I use

public function updateListId($list_id, $model)
{
    $id = $model->id;
    $model->updateByPk($id,array('list_id'=>$list_id));
}

then it updates. Could anyone explain what is happening here?

Upvotes: 0

Views: 253

Answers (1)

Justinas
Justinas

Reputation: 43441

Since you have $model = new Recipient, you can use

 $model->id = $id;
 $model->save(); // Here you can pass array to save method to save only specified columns

instead of

Recipient::model()->updateListId($id, $model)

OR if you wish to do it with model function:

// controller:
$model->updateListId = $id;
$model->save();

// model Recipient
public function setUpdateListId($id) {
    $this->id = $id;
}

Upvotes: 1

Related Questions