我想跑yii migrate
,但它顯示了以下錯誤:如何在Yii2中使用Migration創建複合主鍵?
create table news-cate ...Exception: SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
The SQL being executed was: CREATE TABLE `news-cate` (
`news-id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`cate-id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
這裏是我的代碼:
class m150821_083020_create_newscate_table extends Migration
{
public function safeUp()
{
$this->createTable('news-cate', [
'news-id' => $this->primaryKey(),
'cate-id' => $this->primaryKey(),
]);
$this->addForeignKey("fk_news_cate_nid", "news-cate", "news-id", "news", "id", "RESTRICT", "CASCADE");
$this->addForeignKey("fk_news_cate_cid", "news-cate", "cate-id", "category", "id", "RESTRICT", "CASCADE");
}
public function safeDown()
{
echo "m150821_083020_create_newscate_table cannot be reverted.\n";
$this->dropTable("news-cate");
return false;
}
}
因此,如何在Yii2使用遷移來建立複合主鍵?
這也是創建非整數類型主鍵的最佳方式。 –
感謝您的解決方案! –