开发者

Saving row after populating from Array - Zend

Once again a Zend Framework question! Any help is appreciated.

I have a DB table class which i want to use to insert/update rows when a form is posted, and i would like to use the save() method so it can all go through the same method.


//Users Db Table class
class DBTables_Users extends Zend_Db_Table_Abstract
{
    protected $_name = "users";
    protected $_primary = "userID";
}

So here is 开发者_Python百科my test code...


$userArray = array( 'userID' => 1,
      'firstName' => 'Test',
      'lastName' => 'Test',
      'emailAddress' => 'test@hotmail.com'
      );

$user = new DBTables_Users();

$newUserRow = $user->createRow($userArray);

$newUserRow->save();

This works perfectly without the "userID" item and inserts fine, but if i add that in it tries to insert it again and errors with a duplicate key error.

To me the row should acknowledge the presence of the primary key and use it as the where clause to update the row. However after delving into the code the only thing that it checks, to determine whether its an insert or update, is the presence of the "_cleanData" variable which is populated on construction if the config has a "data" option which it doesnt when using the createRow method.

Am i going about this the wrong way or does it need an ugly fix of setting the _cleanData property myself in an override?

Cheers Stuart


Surely if the entry is a new one you wont have an ID being passed from your form?

Can't you do a quick check if that is null or empty then call an insert rather than the update?

Don't try and do too many things with one method, if they do a different task seperate them out.

Heres an example of my insert / update methods situated in a class which extends Zend_Db_Table (Zend Framework 1.8)

public function insertQuote($quote)
    {
        $data = array('id'=>null,'quote'=>$quote, 'dateCreated'=>NOW());
        $id = $this->insert($data);

        return $id;
    }

public function updateQuote($id, $quote)
    {
        $data = array(
        'quote'=>$quote
        );
        $this->update($data, 'id = ' . (int)$id);
    }


Such a change would make it impossible to insert a row with user-specified primary key (e.g. natural primary keys, pre-fetched from a sequence). It can't assume the table already contains the row, just based on the fact that the array contains the primary key.

You can write a new function, similar to createRow, that constructs the row instance with 'stored' => true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜