LoginSignup
1
1

More than 5 years have passed since last update.

Zendframework2.3.3でjoinをする時、同じcolumnが2個あってダメだぜって言われるエラーの解消方法

Posted at

zendframework2(zf2)でmodelでjoinをしていると、以下error文が出る

 Statement could not be executed (42S21 - 1060 - Duplicate column name 'id')

原因は

 「joinした時に、2つのテーブルに同じcolumn名が存在するため」
 同じの2つはダメだぜ、と上のようなエラー文が出てしまう

case study

 ・テーブル1
   ーTabel名:Cost
   ーColumn:id, user_id, cost
   ーデータ:1, 1, 100
 ・テーブル2
   ーTable名:User
   ーColumn:id, name, email
   ーデータ:1, taro, taro@example.com
 というテーブルが存在したとする。
 これらを以下のようにjoinさせてみる

        $select = $sql->select();
        $select->from('User')
        ->join('Cost','Cost.user_id = User.id");

このとき、何もしないと、実質view側には

(id => 1, name => taro, email => taro@example.com, id => 1, user_id=>2, cost=>100)

が送られるため

Statement could not be executed (42S21 - 1060 - Duplicate column name 'id')

というエラーが出てしまう。

そこで、以下のようにjoinの後に
  array('変更後の名前' => '元々のcolumn名')
を追加してあげる

$select = $sql->select();
$select->from('User')
->join('Cost','Cost.user_id = User.id",
array('cost_id' => 'id',
)
);

するとview側では

(id => 1, name => taro, email => taro@example.com, cost_id => 1, user_id=>2, cost=>100)


joinされる側のテーブルのcolumn名を変更して送られるので
本エラーが回避できる

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1