We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 21872
    • 95 Posts
    I have a query that I am trying to translate to modx/xpdo. I was able to figure out the basics but am getting stuck when I try to add a subquery. In SQL, it looks like this:

    SELECT `title` , `id` , `type`
    FROM `mytable`
    WHERE `status` = 1
    AND `type` NOT
    IN (
    	'foo', 'bar', 'baz', 'bacon', 'ham', 'eggs'
    )
    AND `id` NOT
    IN (
    	(
    	SELECT `id`
    	FROM `mytable`
    	WHERE `title` LIKE '%Test%'
    	)
    )


    in modx/xpdo I have this:

    $query = $modx->newQuery('Mytable');
    $query->select(array('title', 'id', 'type'));
    $query->where(array(
    'status:=' => 1,
    'type:NOT IN' => array('foo', 'bar', 'baz', 'bacon', 'ham', 'eggs')
    ));


    I tried a variety of things to add the subquery, but they all either failed or returned just the result of the subquery. Would someone mind explaining what I need to do?
      • 22303 MODX Staff
      • 10,725 Posts
      Just add the subquery:

      <?php
      $query = $modx->newQuery('Mytable');
      $query->select(array('title', 'id', 'type'));
      $query->where(array(
      'status:=' => 1,
      'type:NOT IN' => array('foo', 'bar', 'baz', 'bacon', 'ham', 'eggs'),
      "`id` NOT IN (SELECT `id` FROM `mytable` WHERE `title` LIKE '%Test%')"
      ));
      
        • 21872
        • 95 Posts
        Thanks! I was trying to write it using the same syntax as the rest of the query, I didn’t realize you could quote the SQL like that.