我正在尝试访问通讯录。我收到了以下错误
Error: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'Contacts'
如果您使用SQL关键字作为表列名,则可以在config / app.php中为数据库连接启用标识符引用。
如何在表关联中设置Alias()?
ContactsController.php
public function index()
{
$this->paginate = [
'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status',
'Secteurs', 'Products']
];
$contacts = $this->paginate($this->Contacts);
$this->set(compact('contacts'));
}
public function view($id = null)
{
$contact = $this->Contacts->get($id, [
'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status',
'Secteurs', 'Products', 'Leads', 'Accounts']
]);
$this->set('contact', $contact);
}
ContactsTable.php
$this->setTable('contacts');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_type_id'
]);
$this->belongsTo('Leads', [
'foreignKey' => 'lead_id'
]);
$this->belongsTo('SourceProspects', [
'foreignKey' => 'source_prospect_id'
]);
$this->belongsTo('Accounts', [
'foreignKey' => 'account_id'
]);
$this->belongsTo('Status', [
'foreignKey' => 'statut_id'
]);
$this->belongsTo('Secteurs', [
'foreignKey' => 'secteur_id'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id'
]);
$this->hasMany('Accounts', [
'foreignKey' => 'contact_id'
]);
$this->hasMany('Leads', [
'foreignKey' => 'contact_id'
]);
}
答案 0 :(得分:1)
这个问题似乎在ContractsTable这里
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_type_id'
]);
以这种方式,cake将Contacts表与自身连接起来,从而创建一个非唯一的别名
也许只是一个错字,你想做
$this->belongsTo('ContactTypes', [
'foreignKey' => 'contact_type_id'
]);
但是如果您确实想要使用该关系,那么您必须为已连接的Contacts表添加别名
$this->belongsTo('ParentContacts', [ // choose your alias here
'className' => 'Contacts'
'foreignKey' => 'contact_type_id'
]);
所以每次你必须引用连接表时你都可以做类似
的事情'contain' => [
...,
'ParentContacts',
],