php - 从 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
谢谢
解决方案
您可以通过添加以下方法结束关系来解决此问题
withPivot(['value']);
public function attributes()
{
return $this->belongsToMany('App\Attribute')->withPivot(['value']);
}
并且
public function products()
{
return $this->belongsToMany('App\Product')->withPivot(['value']);
}
推荐阅读
- python - 这两种计算文本列中两个单词出现次数的方法有什么区别?
- excel - 从另一个 excel 文件运行存在于一个 excel 文件中的宏
- matlab - 如何在 Matlab 中将静止情节更改为电影?
- ruby - 如何使用每个 Testrail 的 add_result 和多个测试运行
- typescript - 所有对象属性都有不同的键但属于同一类型
- postgresql - 关于时区的 PostgreSQL 提取函数
- javascript - 多个、单个输入文件表单字段
- ios - Apple 在向我们的服务器发送应用内购买请求时使用哪种国家代码格式?
- javascript - js es6 类注册
- java - 允许无效调用的返回语句