从 Laravel 中的多对多关系中获取列值

Get column value from Many to Many Relationship in Laravel

这是我的表结构:

Attribute.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
   protected $guarded = [];

   public function products()
   {
       return $this->belongsToMany('App\Product');
   }

}

Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
   protected $guarded = [];

   public function attributes()
   {
       return $this->belongsToMany('App\Attribute');
   }

}

我想获取每一行的 value 列。
我应该在我的控制器中编写什么代码来访问这个 value?
Laravel版本:6.9.0
谢谢

您可以通过添加以下结束关系的方法来解决此问题

withPivot(['value']);
public function attributes()
{
    return $this->belongsToMany('App\Attribute')->withPivot(['value']);
}

还有

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot(['value']);
}

当我们实现Many To Many关系时,它默认创建一个中间table

In your case that table is attribute_product table, we might reference this table as Pivot table.

这个 tables 值是由那些模型通过 pivot 属性名称检索的,如下所示:

$product = App\Product::find(1);

foreach ($product->attributes as $attribute) {
    echo $attribute->pivot->product_id;
}

在 (Pivot table)

中添加额外列

默认情况下,只有模型键 [$attribute_id$product_id] 会出现在 attribute_product table 上。如果您的 pivot table 包含额外的属性,您必须在定义关系时指定它们:

return $this->belongsToMany('App\Attribute')->withPivot('column1', 'column2','value');

pivot 属性名称更改为您的名字

您可能希望将中间 table 访问器重命名为 values 而不是 pivot

return $this->belongsToMany('App\Attribute')
                ->as('values')

然后您将通过 $attribute->values->product_id 而不是 $attribute->pivot->product_id

检索