我有三个表,它们是:
联系人
位置
关联联系人
在我的模型中,我设置了Polymorphs ...
AssociationContact
public function contact()
{
return $this->morphTo();
}
客户
public function contact()
{
return $this->morphToMany(
// the related model
'App\Models\AssociationContact',
// the relationship name
'contact',
// the table name, which would otherwise be derived from the relationship name - twowordables
'association_contacts',
// the foreign key will be twowordable_id, derived from the relationship name, which you're adhering to
'association_contact_id',
// the 'other' key, which would otherwise be derived from the related model's snake case name - two_word_id
'association_contacts_id'
);
}
运行以下代码时:
$clients = Client::all();
foreach($clients as $client)
{
echo "<pre>";
print_r($client->contact);
echo "</pre>";
}
我收到以下错误:
Syntax error or access violation: 1066 Not unique table/alias: 'association_contacts' (SQL: select `association_contacts`.*, `association_contacts`.`association_contact_id` as `pivot_association_contact_id`, `association_contacts`.`association_contacts_id` as `pivot_association_contacts_id`, `association_contacts`.`contact_type` as `pivot_contact_type` from `association_contacts` inner join `association_contacts` on `association_contacts`.`id` = `association_contacts`.`association_contacts_id` where `association_contacts`.`association_contact_id` = 7 and `association_contacts`.`contact_type` = App\Models\Client)
这一定是我建立模型关系的方式,但是不确定我做错了什么。
欢呼
答案 0 :(得分:0)
将此内容放入 AssociationContact :
public function contact()
{
return $this->morphTo(null,'contacts_type','association_contacts_id');
}
将您的客户表中的关系更改为此:
public function contact()
{
return $this->morphMany('App\Models\Contact','contact','contacts_type','association_contacts_id');
}
这应该有效。