Zend 2 - TableGateway Where子句

时间:2012-11-11 18:42:49

标签: zend-framework2 tablegateway

您好我正在尝试使用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 . '%';

}

但我无法找到正确的方法。

编辑(12/11/2012 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子句的示例。我可能错过了一些东西,但我不认为这很明显。

1 个答案:

答案 0 :(得分:10)

为什么人们会忽略official documentation?简单的例子是:

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

但是,您可以为select()函数提供类型为Zend\Db\Sql\Where的参数。 this part of the official documentation再次帮助很多。使用Where,您可以执行更清晰的代码,例如:

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

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

希望这会对你有所帮助。不要忽视文档! ;)