ZendFramework 2:语法错误或访问冲突:1066不唯一的表/别名:

时间:2012-11-02 20:55:18

标签: zend-db zend-framework2 zend-paginator

我是Zendframework 2的新手。我正在尝试连接两个表并显示结果。

这两张表是。 作品和艺术家。表格基于artist_id加入。

步骤1>在Model中创建了2个类(Works,Artist) 步骤2>在WorksTable中,我有以下代码

class WorksTable extends AbstractTableGateway
{
     protected $table ='works';

    public function __construct(Adapter $adapter)
        {

        $this->adapter = $adapter;
        $this->resultSetPrototype = new HydratingResultSet(
                new ArraySerializableHydrator(),
                new Works()
        );
        $this->resultSetPrototype->buffer(); 
        $this->initialize();
    }

    public function fetchAll()
    {
        $select = $this->getSql()->select();
        $select->join('works','artists.artist_id = artist_id ');


        //create paginator object to display records
        $paginator =  new Paginator(
                new DbSelect($select, $this->adapter, $this->resultSetPrototype)
        );

        return $paginator;

    }

}
<步骤3>在控制器中我定义了以下代码

public function searchAction()
    { 
        $request = $this->getRequest();
        $paginator = $this->getWorksTable()->fetchAll();
 //         $paginator->setItemCountPerPage(12);
        $vm = new ViewModel(array(
                'poster' => $paginator,
        ));
        $vm->setVariable('paginator', $paginator);
        return $vm;   
    }

对于声明$ paginator-&gt; setItemCountPerPage(12);得到错误

消息:

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'works'

有没有人遇到过这个错误?关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:0)

你将works表连接到自身,mysql将它视为两个单独的表连接但具有相同的名称,因此错误。

为您加入的表使用别名:

$select = $this->getSql()->select();
$select->join(array('w' => 'works'),'artists.artist_id = artist_id '); 

但看起来它只是错字,表格应为artists

答案 1 :(得分:0)

没有使用artists表开始查询。并且在加入时也没有使用works表。

 use Zend\Paginator\Adapter\DbSelect;
 use Zend\Db\Sql\Sql;
 public function fetchAll()
 {
    $sql = new Sql($this->tableGateway->getAdapter());
    $select = new Select();
    $select->from("artists");
    $select->columns(array('*'));
    $select->join('works','artists.artist_id = works.artist_id',array('your_wanted_column_names,don't mention again artist_id here because there should be a error'));

    $paginator =  new Paginator(
            new DbSelect($select, $this->adapter, $this->resultSetPrototype)
    );

    return $paginator;