Laravel 9中如何获取关联中间表第三列的AttributeValue值
解决方法
1. 修正模型关联
你的中间表包含三个外键,需要调整模型关联配置,要么在Product与Attribute的关联中嵌套AttributeValue,要么直接给Product添加与AttributeValue的多对多关联:
Product 模型代码
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Product extends Model { // 关联属性,同时携带中间表的attribute_value_id及对应属性值模型 public function attributes() { return $this->belongsToMany(Attribute::class, 'attribute_product') ->withPivot('attribute_value_id') ->with('attributeValue'); } // 直接关联属性值,获取value字段更便捷 public function attributeValues() { return $this->belongsToMany(AttributeValue::class, 'attribute_product', 'product_id', 'attribute_value_id') ->withPivot('attribute_id'); } }
Attribute 模型代码
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Attribute extends Model { // 关联对应属性值模型,外键对应关系需匹配你的表结构 public function attributeValue() { return $this->belongsTo(AttributeValue::class, 'id', 'attribute_id'); } }
2. 控制器中正确获取value字段
不要直接操作中间表返回的整数ID,需通过关联模型获取属性值:
方法一:通过属性关联取值
$product = Product::with('attributes.attributeValue')->find($你的商品ID); foreach ($product->attributes as $attribute) { // 从关联的attributeValue模型中获取value字段 $value = $attribute->attributeValue->value; // 编写你的业务逻辑 }
方法二:直接通过属性值关联取值
$product = Product::with('attributeValues')->find($你的商品ID); foreach ($product->attributeValues as $attrValue) { // 直接获取value字段 $value = $attrValue->value; // 编写你的业务逻辑 }
错误原因说明
你触发的“Attempt to read property 'value' on int”错误,是因为你直接访问了中间表返回的attribute_value_id整数字段,尝试对整数调用->value属性——整数不存在该属性,必须通过模型关联将ID转化为AttributeValue实例后,才能访问其value字段。
内容的提问来源于stack exchange,提问作者inocent
相关产品推荐
相关产品推荐

