Context
In Laravel/Lumen 5.5 I have a many-to-many relation defined in my model class SchemaTypes
, using a pivot tabel schema_parent_type
:
public function parents()
{
return $this->belongsToMany('SchemaParentType', 'schema_parent_type', 'type_id', 'parent_id' );
}
I can attach a new parent without problems using this code:
$type = SchemaTypes::where('name', $parentName)->first();
if ( $type)
{
$type->parents()->attach($parent->id);
}
When I check the table schema_parent_type
after attaching a new 'parent' it looks perfect.
Problem
The problem arises when I want to query for all parents given a specific object. When I use this code:
$type = SchemaTypes::where('name', $parentName)->first();
$parents = $type->parents()->get();
this results in the following error:
SQLSTATE[42000]: Syntax error or access violation:
1066 Not unique table/alias: 'schema_parent_type'
(SQL: select `schema_parent_type`.*, `schema_parent_type`.`type_id` as `pivot_type_id`, `schema_parent_type`.`parent_id` as `pivot_parent_id` from `schema_parent_type` inner join `schema_parent_type` on `schema_parent_type`.`id` = `schema_parent_type`.`parent_id` where `schema_parent_type`.`type_id` = 110 and `schema_parent_type`.`deleted_at` is null)
Question
What is the reason that calling $type->parents()->get()
produces this error? How can I solve this?
Any comments or answers are welcome.
You need to change the first argument to another model:
return $this->belongsToMany('SchemaTypes', 'schema_parent_type', 'type_id', 'parent_id' );
More information can be found here: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship. Look at David Lartey his note.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments