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)
I haven't got this problem before.
Temporary solution
Because the code above does not work, I have created another workaround method, which works, but I doubt (pretty sure, actually) this is 'the way to go':
public function getParentTypes()
{
$parents = SchemaParentType::where('type_id', $this->id)->get();
$result = [];
if ($parents){
foreach ($parents as $parent){
$type = SchemaTypes::where('id' , $parent->parent_id)->first();
if ($type)
{
$result[] = $type->name;
}
}
}
return $result;
}
Question
What is the reason that calling $type->parents()->get() produces this error? How can I solve this?
Any comments or answers are welcome.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire