2

嗨,我正在尝试掌握 Zend 2,但我在表网关中的 where 子句方面遇到了一些问题。

下面是我的表类:

//module\Detectos\src\Detectos\Model\OperatingSystemTable.php
namespace Detectos\Model;

use Zend\Db\TableGateway\TableGateway;

class OperatingSystemsTable
{

    public function findOs($userAgent)
    {

        $resultSet = $this->tableGateway->select();

        foreach ($resultSet as $osRow)
        {
            //check if the OS pattern of this row matches the user agent passed in
            if (preg_match('/' . $osRow->getOperatingSystemPattern() . '/i', $userAgent)) {
                return $osRow; // Operating system was matched so return $oses key
            }
        }
        return 'Unknown'; // Cannot find operating system so return Unknown
    }
}

模型是这样的:

class Detectos
{
    public $id;
    public $operating_system;
    public $operating_system_pattern;

    public function exchangeArray($data)
    {
        $this->id                       = (isset($data['id']))                              ? $data['id']                       : null;
        $this->operating_system         = (isset($data['operating_system  ']))              ? $data['operating_system  ']       : null;
        $this->operating_system_pattern = (isset($data['operating_system_pattern']))        ? $data['operating_system_pattern'] : null;

    }

    public function getOperatingSystemPattern()
    {
        return $this->operating_system_pattern;
    }
}

我有什么作品,但我真的应该能够做类似的事情:

public function findOs($userAgent)
{

    $resultSet = $this->tableGateway->select()->where('operating_system_pattern like %' . $userAgent . '%';

}

但我想不出正确的方法来做到这一点。

编辑(2012 年 12 月 11 日 07:53):我从 Sam 的回答中尝试了以下内容,但出现错误:

$spec = function (Where $where) {
    $where->like('operating_system_type', '%' . $this->userAgent . '%');
};


$resultSet = $this->tableGateway->select($spec);

但出现以下错误:

Catchable fatal error: Argument 1 passed to Detectos\Model\OperatingSystemsTable::Detectos\Model\{closure}() must be an instance of Detectos\Model\Where, instance of Zend\Db\Sql\Select given.

我还想补充一点,我已经阅读了文档并遵循了教程。没有提到在那里使用 Zend\Db\Sql。我无法在 tableGateway 中使用高级 where 子句的示例。我可能遗漏了一些东西,但我认为这并不明显。

4

1 回答 1

11

为什么人们忽略官方文档?最简单的例子是这样的:

$artistTable = new TableGateway('artist', $adapter);
$rowset = $artistTable->select(array('id' => 2));

However, you can give the select() function an argument of type Zend\Db\Sql\Where. Again this part of the official documentation helps a lot. With Where you can do cleaner code things like:

$where = new Where();    
$where->like('username', 'ralph%');

$this->tableGateway->select($where)

Hope this helps you a bit. Don't ignore the docs! ;)

于 2012-11-12T06:29:01.687 回答