简体   繁体   中英

Zend Framework 2 "select where not in"

I have this simple query where I have a $posts Array that contains IDs of certain posts. And I am selecting the files associated with these posts basically:

        ->from(
            ['DO' => 'DOCUMENT']
        )
        ->columns(
            [
                'POST_ID',
                'FILENAME'
            ]
        )
        ->where('DO.FILENAME LIKE "%'.$format.'%"')
        ->where(['DO.POST_ID' => $posts])
        ->order('DO.FILENAME DESC');

Now I want to select the files that are not related to these posts. So I need to do opposite of this:

        ->where(['DO.POST_ID' => $posts])

I cannot figure out how?

You need to use NOT IN operation

   ->from(
            ['DO' => 'DOCUMENT']
        )
        ->columns(
            [
                'POST_ID',
                'FILENAME'
            ]
        )
        ->where('DO.FILENAME LIKE "%'.$format.'%"')
        ->where->addPredicate(new Zend\Db\Sql\Predicate\Expression('DO.POST_ID NOT IN (?)', array($posts)))
        ->order('DO.FILENAME DESC');

use Zend\Db\Sql\Predicate\NotIn;

$adapter = $this->tableGateway->getAdapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('produto');
$select->where->addPredicate->notIn('DO.POST_ID', [1,3,5]);
$select->order('status ASC');
$selectStr = $sql->getSqlStringForSqlObject($select);
echo $selectStr;
$results = $adapter->query($selectStr, $adapter::QUERY_MODE_EXECUTE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM