【问题标题】:Error: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'Coupons'错误:SQLSTATE [42000]:语法错误或访问冲突:1066 不是唯一的表/别名:“优惠券”
【发布时间】:2016-12-03 01:53:12
【问题描述】:

我正在尝试创建一个向我的数据库添加数据的表单。我的桌子叫做优惠券,我有以下代码:

//CouponsController.php
public function addCoupon() {
   $coupon = $this->Coupons->newEntity();
       if ($this->request->is('post')) {
         $coupon = $this->Coupons->patchEntity($coupon, $this->request->data);
         if ($this->Coupons->save($coupon)) {
             $this->Flash->success(__('The coupon has been saved.'));
             return $this->redirect(['action' => 'index']);
             } else {
             $this->Flash->error(__('The coupon could not be saved. Please, try again.'));
             }
        }
        $coupons = $this->Coupons->Coupons->find('list', ['limit' => 200]);
        $this->set(compact('coupon', 'coupons'));
        $this->set('_serialize', ['coupon']);
}

//CouponsTable.php
public function initialize(array $config)
{
    parent::initialize($config);
    $this->table('coupons');
    $this->displayField('coupon_id');
    $this->primaryKey('coupon_id');
    $this->belongsTo('Coupons', [
        'foreignKey' => 'coupon_id',
        'joinType' => 'INNER'
    ]);
}

//add_coupon.ctp
<h3>Add Coupon</h3>
<?php 
    echo $this->Form->create(null,['url' => ['action' => 'addCoupon']]);
    echo $this->Form->input('coupon_code');
    echo $this->Form->input('expiration_date');
    echo $this->Form->input('discount_amount');
    echo $this->Form->input('usage_limit');
    echo $this->Form->input('domain_limit');
    echo $this->Form->input('description');
    echo $this->Form->input('type');
    echo $this->Form->button('Submit');
    echo $this->Form->end();
?>

当我点击提交时,数据会存储在数据库中,但我会看到“错误:SQLSTATE[42000]:语法错误或访问冲突:1066 Not unique table/alias:'Coupons'”。 SQL查询: 选择 Coupons.coupon_id AS Coupons__coupon_id, Coupons.coupon_code AS Coupons__coupon_code, Coupons.expiration_date AS Coupons__expiration_date, Coupons.discount_amount AS Coupons__discount_amount, Coupons.usage_limit AS Coupons__usage_limit, Coupons.domain_limit AS @987654372 .description AS Coupons__description, Coupons.type AS Coupons__type FROM coupons Coupons INNER JOIN coupons Coupons ON Coupons.coupon_id = (Coupons.coupon_id) LIMIT 20 OFFSET 0 那么这里有什么问题呢?

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    改变

    $this->Coupons->Coupons->find('list', ['limit' => 200]) 
    

    $this->Coupons->find('list', ['limit' => 200])
    

    您通过引用它两次导致表连接到自身。

    另外,删除此代码。我认为没有理由加入反对表:

    $this->belongsTo('Coupons', [
        'foreignKey' => 'coupon_id',
        'joinType' => 'INNER'
    ]);
    

    【讨论】:

      【解决方案2】:

      coupon_id 是您的主键吗?如果是,那么它违反了 cakephp 命名约定。

      【讨论】:

        猜你喜欢
        • 2015-04-01
        • 1970-01-01
        • 2016-02-06
        • 2018-12-07
        • 2019-03-15
        • 2015-09-12
        • 2022-01-25
        • 2015-10-12
        • 2023-04-01
        相关资源
        最近更新 更多