Translating a query to use Zend_Db_Select

怎甘沉沦 提交于 2020-01-12 03:49:05

问题


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


来源:https://stackoverflow.com/questions/520131/translating-a-query-to-use-zend-db-select

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