Trying to implement a polymorphic many-to-many relationship, similar to the one in the documentation.
In my case, for label instead of tag. And using different table names
apples / oranges / ...
id - integer
name - string
label_types
id - integer
name - string
labels
label_type_id - integer -- foreign ID for LabelType
labeling_type - string
labeling_id - integer - ID of the model this labelType is used for
// Apple / Orange / ...
public function labels(LabelType $type = null)
{
// need to provide table name, as expected default table name is labelings
return $this->morphToMany(Label::class, 'labeling', 'labels');
}
// Label
public function apples()
{
return $this->morphedByMany(Apple::class, 'labeling', 'labels');
}
public function oranges()
{
return $this->morphedByMany(Orange::class, 'labeling', 'labels');
}
This results in an error.
$apple->labels;
Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'labels'
select
`labels`.*,
`labels`.`label_id` as `pivot_label_id`,
`labels`.`label_type` as `pivot_label_type`
from
`labels`
inner join `labels` on `labels`.`id` = `labels`.`label_id`
where
`labels`.`label_id` = 1
and `labels`.`label_type` = 'App\Models\Apple'
In the example above I have added the table name to morphToMany().
Same error when using labelings as table name and adding to Label model: protected $table = 'labelings';
How do I get this to work? I do want to use label_types as it better fits with the rest of my application.
I looked at other polymorphic questions on Stackoverflow, but could not find an answer.