【问题标题】:Laravel many to many relationship, add more objects into "pivot"?Laravel 多对多关系,将更多对象添加到“pivot”中?
【发布时间】:2015-01-02 10:42:28
【问题描述】:

通常多对多关系会返回如下内容:

Product::with('brands')->find(4);

{
  id: 4
  name: 
  price:
  brands: [
    id: 6
    pivot: {
      product_id: 4,
      brand_id: 6,
      // withPivot fields goes here if specified.
      // I want to add extra fields here too, unrelated to the database. e.g. :
      foo: 'bar'
    }

  ],
  suppliers: [

  ]
}

这是在Product.php:

public function brands()
{
  return $this->belongsToMany('Brand');
}

我们是否可以控制 pivot 对象中的内容?我知道它会吐出两个外键 ID 以及您包含的任何 withPivot,但我想添加另一个属性,但我不确定该怎么做。 Laravel 在幕后神奇地完成了所有这些多对多的事情。

这样做会产生错误(我正在尝试将foo: "bar" 添加到每个枢轴)

public function brands()
{
  $brands = $this->belongsToMany('Brand'); 

  foreach($brands as $brand)
  {
    $brand->foo = 'bar';
  }

  return $brands;
}

【问题讨论】:

  • 您要添加的究竟是什么?通常将其添加到相关模型(在这种情况下为Brand)应该没问题。
  • 我已经编辑了我的帖子以澄清,但我认为我不能让它比这更简单。这与Brand 无关,更多的是与控制一般的 json 输出有关。
  • 我明白了。但是值是静态的还是从哪里得到的?
  • 目前是静态的,但我计划添加动态值,例如另一个结果集,例如Supplier::find($brand->supplier_id).

标签: php laravel pivot


【解决方案1】:

由于您有兴趣修改它的 JSON 输出,您可以覆盖 toArray() 并在其中添加属性:

public function toArray(){
    foreach($this->brands as $brand){
        $brand->pivot->foo = 'bar';
    }
    return parent::toArray();
}

更新

为了避免不必要地加载 brands 关系。可以先获取数组,检查关系是否加载完毕

public function toArray(){
    $array = parent::toArray();
    if(isset($array['brands'])){
        foreach($array['brands'] as &$brand){
            $brand['pivot']['foo'] = 'bar';
        }
    }
    return $array;
}

请注意,我在$brand 之前使用& 通过引用传递数组,而不仅仅是通过值传递。否则我将不得不在循环内执行$array['brands'][$index]['pivot']['foo'] =

【讨论】:

  • 完美。正是我想要的!
  • 这适用于Product,但如果我调用另一个与Product 具有多对多关系的模型,它总是会在你的foreach 循环中触发$this->brands,这是不需要的.这导致始终显示产品的品牌。我试过$hidden = ['brands'];,但我知道这是错误的。有没有办法解决这个问题?
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 2014-04-10
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多