[英]Pivot Table with 3 Columns to get the value in Laravel 9
我是 Laravel 的新人,我正在尝试从 pivot 表中的第三列 id 中获取值
我有 3 个表,第 4 个表是 pivot 表,所以我的表结构如下
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('category_id')->constrained();
$table->timestamps();
});
Schema::create('attributes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('attribute_values', function (Blueprint $table) {
$table->id();
$table->string('value');
$table->foreignId('attribute_id')->constrained();
$table->timestamps();
});
Schema::create('attribute_product', function (Blueprint $table) {
$table->foreignId('product_id')->constrained();
$table->foreignId('attribute_id')->constrained();
$table->foreignId('attribute_value_id')->constrained();
});
<<<<<<<<<<< 表格模型>>>>>>>>>>>>>>>>>>>>>> 1.表格产品
class Product extends Model
{
use HasFactory;
public function attributes()
{
return $this->belongsToMany(Attribute::class)->using(AttributeProduct::class)->withPivot('attribute_value_id');
}
}
2.表格属性
class Attribute extends Model
{
use HasFactory;
public function products()
{
return $this->belongsToMany(Product::class)->using(AttributeProduct::class)->withPivot('attribute_value_id');
}
}
class AttributeValue extends Model
{
use HasFactory;
protected $guarded = [];
public function attribute_product()
{
return $this->hasMany(AttributeProduct::class, 'attribute_value_id');
}
}
而且我还制作了一张 model 的 pivot 表
use Illuminate\Database\Eloquent\Relations\Pivot;
class AttributeProduct extends Pivot
{
use HasFactory;
public function value()
{
return $this->belongsTo(AttributeValue::class,'attribute_value_id');
}
}
<<<<<<<<<<<<<<表格中的数据>>>>>>>>>>>>>>>>>>>>>>>>>>
ID TITLE category_id
6 Samsung S22 2
ID NAME
1 SIZE
2 COLOR
ID VALUE attribute_id
1 SM 1
2 M 1
3 RED 2
4 BLUE 2
product_id attribute_id attribute_value_id
6 1 1
6 2 4
现在我在 controller 中使用这些命令来查找值
$p = Product::find(6);
foreach($p->attributes as $value){
echo $value->name." = ". $value->pivot->attribute_value_id->value."<br>";
}
当我尝试从 pivot 表中获取基于 attribute_value_id 的值时,它给了我这个错误
ErrorException Attempt to read property "value" on int
那么我该如何解决这个问题。
谢谢
pivot 关系value
应该是hasOne
,而不是belongsTo
。
class AttributeProduct extends Pivot
{
use HasFactory;
public function value()
{
return $this->hasOne(AttributeValue::class, 'id', 'attribute_value_id');
}
}
所以在你的foreach
中,你现在可以这样做:
foreach($p->attributes as $attribute){
echo $attribute->name." = ". $attribute->pivot->value->value."<br>";
}
还要尽量保持变量名称的直截了当。 如果$value
显然是一个$attribute
,不要将$p->attributes as $value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.