Translating a query to use Zend_Db_Select

2019-03-16 02:53发布

问题:

I'm having some problems translating this query to use ZF's Zend_Db_Select:

SELECT b.id, b.title, b.description 
FROM memberships AS m
JOIN blogs AS b ON b.id = m.blog_id 
WHERE m.user_id = ? 
ORDER BY m.created
LIMIT 0, 30

(this query works and returns results)

Memberships is a link table between blogs and users. It's a simple | id | blog_id | user_id | affair.

Here's what I have so far:

// $table = Zend_Db_Table instance, $id = a user id
$select = $table->select()
->from(array('m' => 'memberships'), array('b.id', 'b.title', 'b.description'))
->join(array('b' => 'blogs'), 'b.id = m.blog_id')
->where('m.user_id = ?', (int) $id)
->order('m.created DESC')
->limit(0, 30);

This is the (strange (to me)) error I'm getting:

#0: Select query cannot join with another table

Occurred on line 211 of D:\...\library\Zend\Db\Table\Select.php.

Thanks for your help.

回答1:

When retrieved from your table object, the statement will be limited to that table I think. The Zend_Db_Table::select() methods returns a Zend_Db_Table_Select object which is a subclass of Zend_Db_Select and imposes this restriction. Try this instead:

$db = Zend_Db::factory( ...options... );
$select = new Zend_Db_Select($adapter);
$select->from( 'my_table_name' )->join( ...

If you prefer, the following should be equivalent:

$db = Zend_Db::factory( ...options... );
$db->select()->from( 'my_table_name' )->join( ...


回答2:

You could also still use the traditional $model->select() object by adding setIntegrityCheck(false), like so.

$select = $table->select()
->setIntegrityCheck(false)
->from(array('m' => 'memberships'), array('b.id', 'b.title', 'b.description'))
->join(array('b' => 'blogs'), 'b.id = m.blog_id')
->where('m.user_id = ?', (int) $id)
->order('m.created DESC')
->limit(0, 30);

This disables the check that is throwing the exception:

#0: Select query cannot join with another table