Zend 2 - TableGateway Where子句

Ayd*_*san 2 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
    }
}
Run Code Online (Sandbox Code Playgroud)

模型是这样的:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有什么作品,但我应该能够做到这样的事情:

public function findOs($userAgent)
{

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

}
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚这样做的正确方法.

编辑(12/11/2012 07:53):我从Sam的回答中尝试了以下内容,但遇到了错误:

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


$resultSet = $this->tableGateway->select($spec);
Run Code Online (Sandbox Code Playgroud)

但得到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*Sam 10

人们为什么忽视官方文件?简单的例子是这样的:

$artistTable = new TableGateway('artist', $adapter);
$rowset = $artistTable->select(array('id' => 2));
Run Code Online (Sandbox Code Playgroud)

但是,您可以为select()函数提供类型的参数Zend\Db\Sql\Where.这部分官方文档再次提供了很多帮助.随着Where你可以做更干净的代码,如:

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

$this->tableGateway->select($where)
Run Code Online (Sandbox Code Playgroud)

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