加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何在模型中更改Zend_Db_Table名称以插入多个表

发布时间:2020-12-13 21:36:24 所属栏目:PHP教程 来源:网络整理
导读:使用Zend Framework,我创建了一个Model来将记录插入数据库.我的问题是,在$this- insert($data)之后如何切换活动表以便我可以将记录插入另一个表? 到目前为止,这是我的代码: class Model_DbTable_Foo extends Zend_Db_Table_Abstract{ protected $_name = '
使用Zend Framework,我创建了一个Model来将记录插入数据库.我的问题是,在$this-> insert($data)之后如何切换活动表以便我可以将记录插入另一个表?

到目前为止,这是我的代码:

class Model_DbTable_Foo extends Zend_Db_Table_Abstract
{
  protected $_name = 'foo';

  public function addFoo($params)
  {
    $data = array(
      'foo' => $params['foo'],);
    $this->insert($data);
    $foo_id = $this->getAdapter()->lastInsertId();

    $data2 = array(
      'bar' => $params['bar']
    );
    // I need to change the Db Table name here.
    $this->insert($data2);
    $bar_id = $this->getAdapter()->lastInsertId();
  }
}

解决方法

Zend_Db_Table是 Table Data Gateway.它

acts as a Gateway to a database table. One instance handles all the rows in the table.

这意味着,每个表有一个类. Model_DbTable_Foo表示数据库中的Foo表,仅表示此表.它不应该在其他表上插入.这就是你要使用另一个表类的原因.最干净的选择是在TDG之上添加另一个层,它知道如何处理多个表的插入,例如

class Model_Gateway_FooBar
{
    protected $_tables;

    public function __construct(Zend_Db_Table_Abstract $foo,Zend_Db_Table_Abstract $bar)
    {
        $this->_tables['foo'] = $foo;
        $this->_tables['bar'] = $bar;
    }

    public function addFoo($data)
    {
        $this->_tables['foo']->insert($data['foo']);
        // yaddayaddayadda
        $this->_tables['bar']->insert($data['bar']);
    }
}

但是,这是你的应用程序,你可以决定不打扰并简单地在Foo类中创建另一个类的新实例并从那里执行插入,例如

$otherTable = new Model_DbTable_Bar;
$otherTable->insert($data);

另一个选择是将逻辑放入控制器,但我不能推荐它,因为这不是控制器的责任,通常是controllers should be kept thin and models should be fat.

在旁注中,当您进行多次插入时,您可能希望使用事务来使两个插入按预期工作,例如,

$this->_tables['foo']->getAdapter()->beginTransaction();

然后根据查询结果commit()或rollback().

另请注意,从ZF1.9开始,您还可以创建Zend_Db_Table的实例,而无需先定义具体的子类,例如

$fooTable = new Zend_Db_Table('foo');

请参阅Zend_Db_Table in the ZF Reference Guide章.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读