Laravel 基本属于很多

问题描述 投票:0回答:1

我有

ProductCollection
模型和
AttributeValue
模型,它们有一个公用表
product_collection_attributes
,其中有 2 列:
product_collection_id
attribute_value_id
,它们是各自表的外键,并且都是主键。

在 ProductCollection 模型中关系是:

public function attributes()
{
  return $this->belongsToMany(AttributeValue::class, 'product_collection_attributes', 'product_collection_id');
}

在 AttributeValue Model 中关系是:

public function product_collections()
{
  return $this->belongsToMany(ProductCollection::class, 'product_collection_attributes', 'attribute_value_id');
}

我的查询是:

$productCollection->attributes()->get()
;返回一个空数组, 但是,如果查询是
DB::table('product_collection_attributes')->where('product_collection_id', $productCollection->id)->get();
,它会返回一个完整的数组!!

最重要的事情这只发生在以下代码之后,这是破坏性的并出现错误:(

Exception: "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2-2' for key 'product_collection_attributes.PRIMARY' (Connection: mysql, SQL: insert into 
product_collection_attributes
 (
attribute_value_id
, 
product_collection_id
) values (2, 2))"
):`

$productCollection->update([
 SOMEINFO...,
 'allow_price_change' => 0
]);
$data['attributes'] = [1,2];
$productCollection->attributes()->delete();
if (isset($data['attributes']) && count($data['attributes'])) {
 $data['attributes'] = array_unique($data['attributes']);
 $data['attributes'] = array_values(array_filter($data['attributes']));
 $productCollection->attributes()->attach($data['attributes']);
}

所以我将上面的代码替换为:

$productCollection->update([
 SOMEINFO...,
 'allow_price_change' => 0
]);
$data['attributes'] = [1,2];
DB::table('product_collection_attributes')->where('product_collection_id', $productCollection->id)->delete();
if (isset($data['attributes']) && count($data['attributes'])) {
 $data['attributes'] = array_unique($data['attributes']);
 $data['attributes'] = array_values(array_filter($data['attributes']));
 $productCollection->attributes()->attach($data['attributes']);
}

现在我遇到了这个问题,

$productCollection->attributes()->get()
不再起作用了!并且只有
DB::table('product_collection_attributes')->where('product_collection_id', $productCollection->id)->get();
有效!!

And note that if I update something in product collection that isn't a boolean all works fine!!, so update $productCollection->update(['name' => 'aaa', ...]) then update attributes will be fine

我不知道为什么,在几乎所有情况下使用

ProductCollection::with(['attributes'])
都很重要,特别是连接,它迫使我改用 DB!

我们该如何解决这个问题?

laravel eloquent relationship laravel-11
1个回答
0
投票

代码似乎正常运行,product_collections() 方法定义中存在潜在问题。它是在 AttributeValue 模型中定义的,但它的命名就像是为了获取相关的 ProductCollections。如果您打算获取相关的 ProductCollections,您应该将 AttributeValue 模型中的关系定义为 ProductCollections() 或类似的东西。

public function productCollections()
{
    return $this->belongsToMany(ProductCollection::class, 'product_collection_attributes', 'attribute_value_id');
}
© www.soinside.com 2019 - 2024. All rights reserved.