首页 > 解决方案 > 从 Laravel 中的多对多关系获取列值

问题描述

这是我的表结构: 在此处输入图像描述

属性.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

   public function products()
   {
       return $this->belongsToMany('App\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
谢谢

标签: phplaravelmany-to-manyrelationship

解决方案


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

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

并且

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

推荐阅读