我已经同步数据,我将一些产品附加到另一个产品作为相关产品,保存和同步方法工作正常,我在编辑部分的问题。
当我尝试加载产品编辑页面时出现此错误:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'product_relatives' (SQL: select `product_relatives`.*, `product_relatives`.`product_id` as `pivot_product_id`, `product_relatives`.`relatives_id` as `pivot_relatives_id` from `product_relatives` inner join `product_relatives` on `product_relatives`.`id` = `product_relatives`.`relatives_id` where `product_relatives`.`product_id` = 49)
this is my edit function
public function edit($id)
{
$product = Product::findOrFail($id);
//another synced data and how i retrieve them
$suboptions = Suboption::all();
$suboptions2 = array();
foreach($suboptions as $suboption) {
$suboptions2[$suboption->id] = $suboption->title;
}
// my issue comes from here
$relatives = ProductRelative::all();
$relatives2 = array();
foreach($relatives as $relative) {
$relatives2[$relative->id] = $relative->title;
}
return view('admin.products.edit', compact('product','suboptions2', 'relatives2'));
}
blade code
{{ Form::label('relatives', 'Relative Products') }}
{{Form::select('relatives[]', $relatives2, null, ['class' => 'form-control tagsselector', 'multiple' => 'multiple'])}}
product model
public function relatives()
{
return $this->belongsToMany(ProductRelative::class, 'product_relatives', 'product_id', 'relatives_id');
}
relatives model
public $timestamps = false;
protected $table = 'product_relatives';
public $fillable = ['product_id', 'relatives_id'];
public function products()
{
return $this->belongsToMany(Product::class);
}
任何想法如何解决?
答案 0 :(得分:1)
失败的SQL语句非常有意义。它正在尝试将表product_relatives加入product_relatives表。因此,抛出的错误Not unique table or alias
仅基于查询才有意义。
下一步是试着想一想Laravel可能会在这里混淆的原因。
由于您尝试使用相同的模型创建belongsToMany,因此您需要这些表
现在,您只需要创建一个模型:
您的产品型号应包含:
public function relatives()
{
return $this->belongsToMany(Product::class, 'product_relative', 'product_id', 'relative_id');
}
您的ProductRelative模型应包含:
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
public function relative()
{
return $this->belongsTo(Product::class, 'relatives_id');
}
问题出现了,因为您使用ProductRelative模型作为数据透视表,并尝试使用与模型本身相同的表名在其中创建BelongsToMany关系。