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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 如何在模型中更改Zend_Db_Table名称以插入多个表脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
使用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.它

这意味着,每个表有一个类. 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章.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 如何在模型中更改Zend_Db_Table名称以插入多个表全部内容,希望文章能够帮你解决php – 如何在模型中更改Zend_Db_Table名称以插入多个表所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。