Zend Framework 2 Db: Make a part of the query negative using Predicate objects

一个人想着一个人 提交于 2020-01-16 04:50:07

问题


How do you negate a part of the query using Zend Framework 2? I'm trying to do the Zend\Db equivalent of this dynamic MySQL query-part:

NOT (`a` = 1 AND `b`IS NULL AND `c` LIKE 'foo')

Right now I have the three query-parts as Predicate objects (Operator, IsNull and Like objects). How can I negate these and put in the where?

Is it possible to convert a Predicate object (like an Operator or IsNull object) to a Sql String?


回答1:


Zend dose not have a out of box solution for this , I wrote a class to do this .

/**
 * Created by PhpStorm.
 * User: Exlord (adeli.farhad@gmail.com)
 * Date: 6/19/14
 * Time: 11:44 AM
 */

namespace System\DB\Sql\Predicate;

use Zend\Db\Sql\Predicate\PredicateInterface;

class Not implements PredicateInterface
{
    /**
     * @var string
     */
    protected $specification = 'NOT (%1$s)';

    protected $expression;

    public function __construct($expression = null)
    {
        $this->expression = $expression;
    }

    /**
     * @param null $expression
     */
    public function setExpression($expression)
    {
        $this->expression = $expression;
    }

    /**
     * @return null
     */
    public function getExpression()
    {
        return $this->expression;
    }

    /**
     * @param  string $specification
     * @return self
     */
    public function setSpecification($specification)
    {
        $this->specification = $specification;
        return $this;
    }

    /**
     * @return string
     */
    public function getSpecification()
    {
        return $this->specification;
    }

    /**
     * @return array
     */
    public function getExpressionData()
    {
        return array(
            array($this->specification, array($this->expression), array(self::TYPE_VALUE))
        );
    }
} 

usage :

$where = new Where();
$where->notIn('id', array(1, 2));
$where->equalTo('name', 'Foo');

$select = new Select('tbl_');
$select->where->addPredicate(new Not($where));

var_dump($select->getSqlString());

output :

string 'SELECT "tbl_".* FROM "tbl_" WHERE NOT ("id" NOT IN ('1', '2') AND "name" = 'Foo')' (length=81)




回答2:


Its more like -

'a' != 1 AND 'b' IS NOT NULL AND 'c' NOT LIKE 'foo'

Try these as individual where conditions.

Eg:

$where = new Where();
$where->notEqualTo('a', 1);
$where->isNotNull('b');
$where->literal('c NOT LIKE ?', array('foo'));


来源:https://stackoverflow.com/questions/24260297/zend-framework-2-db-make-a-part-of-the-query-negative-using-predicate-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!