【问题标题】:How do I access third table via Many-to-Many Relation in Laravel?如何通过 Laravel 中的多对多关系访问第三个表?
【发布时间】:2017-06-25 04:07:57
【问题描述】:

我正在使用 Laravel 5.4 开发一个电子商务网站。这是数据库结构:

Products Table: 

ID - Product Name
1  - Test Mobile



Attributes Table

ID - AttributeName
1  - Network



AttributeValues Table

ID - AttributeID - AttributeValue
1  - 1           - 2G
2  - 1           - 3G
3  - 1           - 4G



ProductAttributes Table

ID - AttributeValueID - ProductID
1  - 2                - 1
2  - 3                - 1

这里是关系:

产品.php

class Product extends Model
{

    public function attributeValues() {
        return $this->belongsToMany('App\AttributeValue', 'attribute_product');
    }

}

属性.php

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


    public function values() {
        return $this->hasMany(AttributeValue::class);
    }
}

属性值.php

class AttributeValue extends Model
{

    public $timestamps = false;

    public function attribute() {
        return $this->belongsTo( App\Attribute::class );
    }

}

我可以使用以下代码访问产品属性值:

$p = App\Product::find(1);
$p->attributeValues;

通过此代码,我能够检索产品属性值。但是我可以访问attributeValues 以及属性名称吗?换句话说,我如何访问属性表以及属性值?将使用哪种关系?

有什么想法吗?建议?

【问题讨论】:

  • @Thomas 你能发一个示例代码吗?
  • 我现在不能,因为要准确理解您当前的问题需要太多时间。你能把问题简化成你期望的输出吗?
  • @Thomas 我想使用属性名称和值对访问产品属性。即:网络:3G。
  • @GopaThemes 您提供的表格描述不太清楚。一个是,attributes 上的产品可能没有参考,id 或者您是否以任何方式错过了它?

标签: php mysql laravel database-design laravel-5.4


【解决方案1】:

我曾经用load方法做过这样的事情,即

$p = App\Product::find(1);
$p->load('attributeValues.attribute');

所以对于每一个attributeValue,得到对应的attribute 它应该也适合你...

PS:我不敢打赌这是最好的方法。但我已经将这种技术用于 Laravel 5.2 项目

【讨论】:

    【解决方案2】:

    你用错地方了,用你在模型中描述关系的名字。

    $product = App\Product::with('attributeValues.attribute')->find(1)
    

    【讨论】:

      【解决方案3】:

      如果 Product belonsToMany AttributeValue,AttributeValue 应该属于ToMany Product。

      产品型号:

      public function attributeValues() {
              return $this->belongsToMany('App\AttributeValue', 'attribute_product');
          }
      

      属性值模型:

      public function products() {
              return $this->belongsToMany('App\Product');
          }
      
      public function attribute() {
          return $this->belongsTo( App\Attribute::class );
      }
      

      属性模型:

        public function values() {
              return $this->hasMany(AttributeValue::class);
          }
      

      还有,

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-01
        • 2020-07-03
        • 2018-05-20
        • 2017-08-07
        • 1970-01-01
        • 2019-02-20
        • 2012-04-30
        • 2022-01-15
        相关资源
        最近更新 更多