0

尝试实现多态多对多关系,类似于文档中的关系。

就我而言, forlabel而不是tag. 并使用不同的表名

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');
    }

这会导致错误。

$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'

在上面的示例中,我已将表名添加morphToMany(). 用作表名并添加到标签模型
时出现相同的错误:labelingsprotected $table = 'labelings';

我怎样才能让它工作?我确实想使用label_types它,因为它更适合我的应用程序的其余部分。
我查看了 Stackoverflow 上的其他多态问题,但找不到答案。

4

0 回答 0