【问题标题】:Get column value from Many to Many Relationship in Laravel从 Laravel 中的多对多关系获取列值
【发布时间】:2020-04-29 07:20:37
【问题描述】:

这是我的表格结构:

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
谢谢

【问题讨论】:

    标签: php laravel many-to-many relationship


    【解决方案1】:

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

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

    还有

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

    【讨论】:

    【解决方案2】:

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

    在您的情况下,该表是 attribute_product 表,我们可以将此表称为 Pivot 表。

    这些模型通过pivot 属性名称检索此表值,如下所示:

    $product = App\Product::find(1);
    
    foreach ($product->attributes as $attribute) {
        echo $attribute->pivot->product_id;
    }
    

    在(数据透视表)中添加额外的列

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

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

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

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

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

    然后你将通过$attribute-&gt;values-&gt;product_id而不是$attribute-&gt;pivot-&gt;product_id检索

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2019-07-17
      相关资源
      最近更新 更多