【问题标题】:Laravel hasMany relation returns ' Not unique table/alias' errorLaravel hasMany 关系返回 'Not unique table/alias' 错误
【发布时间】:2018-05-18 23:25:26
【问题描述】:

上下文

在 Laravel/Lumen 5.5 中,我在模型类 SchemaTypes 中定义了一个多对多关系,使用数据透视表 schema_parent_type

public function parents()
{
    return $this->belongsToMany('SchemaParentType', 'schema_parent_type', 'type_id', 'parent_id' );

}

我可以使用此代码毫无问题地附加新的父级:

$type = SchemaTypes::where('name', $parentName)->first();
if ( $type)
{
      $type->parents()->attach($parent->id);
}

当我在附加一个新的“父级”后检查表 schema_parent_type 时,它看起来很完美。

问题

当我想查询给定特定对象的所有父母时,就会出现问题。当我使用此代码时:

$type = SchemaTypes::where('name', $parentName)->first();
$parents = $type->parents()->get();

这会导致以下错误:

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)

问题

调用$type->parents()->get() 产生此错误的原因是什么?我该如何解决这个问题?

欢迎任何cmets或答案。

【问题讨论】:

    标签: php laravel-5 orm many-to-many lumen


    【解决方案1】:

    您需要将第一个参数更改为另一个模型:

    return $this->belongsToMany('SchemaTyp‌​es', 'schema_parent_type', 'type_id', 'parent_id' );
    

    更多信息可以在这里找到:SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship。看看 David Lartey 他的笔记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多