Model 获取表模型中的默认zend db适配器

Model 获取表模型中的默认zend db适配器,model,zend-framework2,adapter,Model,Zend Framework2,Adapter,如何在表模型中获取默认的db adabter?我想用它来创建一个事务 在database.global.php中: return array( 'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', ), 'al

如何在表模型中获取默认的db adabter?我想用它来创建一个事务

在database.global.php中:

    return array(
   'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=cww;host=localhost',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
    ),
);
现在我想要 my albumTable.php中的
$this->adapter

我试图按如下方式接收:

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Ajax\Model\Album;

class AlbumTable implements ServiceLocatorAwareInterface
{
    protected $tableGateway;
    protected $adapter;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
        $this->adapter  = $this->getServiceLocator()->get('db');    
    }
但我得到了一个错误:

致命错误:类Ajax\Model\AlbumTable包含2个抽象方法 因此必须声明为抽象的或实现剩余的 方法 (Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator, Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator) 在


添加以下功能:

public function getServiceLocator() {
    return $this->serviceLocator;
}


public function setServiceLocator(Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
    $this->serviceLocator= $serviceLocator;
    return $this;
}
然后你可以做:

$this->$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
但是,如果您阅读《入门》,它将解释如何使用service manager工厂构造
表网关
,并传入DbAdapter和其他参数,如:

'RoleTableGateway' => function ($sm) {
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $resultSetPrototype = new ResultSet();
    $resultSetPrototype->setArrayObjectPrototype(new Role());
    return new TableGateway('role', $dbAdapter, null, $resultSetPrototype);
},

使用此选项创建数据库适配器:

$adapter = $this->getServiceLocator()->get('db');
您只能在创建别名后使用“db”。您还可以尝试在\autoload\config\local.php中的locals.php中编写内容。 现在,假设我们要在mySQL中执行一个数据库查询: 创建sql语句并放入变量$sql。 现在,请执行以下操作:

$statement = $adapter->createStatement($sql);
$result = $statement->execute();

希望这有帮助。

谢谢你的回答。我已经设置了tableGetaway,所以我现在使用这个来获取我需要的数据“$this->tableGateway->getAdapter()”;这就是我所需要的:)谢谢,我得到了这个错误“致命错误:在F:\xampp\htdocs\zendtest\module\Application\src\Application\Model\Signup.php的第41行对非对象调用成员函数get()”。请查看我的问题“”,您的解决方案适合我的情况吗?您需要手动将服务定位器或数据库适配器设置到模型类中。有关问题的评论应提供指导。