I have three tables, they are :
Contacts
Locations
Association Contacts
In my models, I've set the Polymorphs...
AssociationContact
public function contact()
{
return $this->morphTo();
}
Client
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'
);
}
When running the following code :
$clients = Client::all();
foreach($clients as $client)
{
echo "<pre>";
print_r($client->contact);
echo "</pre>";
}
I get the following error :
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)
It must be how I've set up the model relations, But not sure what I've done wrong.
Cheers
Put this in AssociationContact:
public function contact()
{
return $this->morphTo(null,'contacts_type','association_contacts_id');
}
Change the relationship in your Client table to this:
public function contact()
{
return $this->morphMany('App\Models\Contact','contact','contacts_type','association_contacts_id');
}
This should work.