php - 如何通过 Laravel 中的多对多关系访问第三个表?

标签 php mysql laravel database-design laravel-5.4

我正在使用 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 以及属性名称吗?换句话说,我如何访问属性表以及属性值?将使用哪种关系?

有什么想法吗?建议?

最佳答案

我曾经用 load 方法做过类似的事情,即

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

因此对于每个attributeValue,得到相应的attribute 它也应该对你有用......

PS: I can't bet this is the best way to do it. But I have used this technique for a Laravel 5.2 project

关于php - 如何通过 Laravel 中的多对多关系访问第三个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42097896/

相关文章:

php - PHP 中的日期时间

php - 将文件从网络服务器保存到数据库中

php - 简单的jquery级联选择

ajax - 在关注 laravel 上构建 AJAX 按钮

php - 创建一个输出用户输入数字的计算页面

php - 如何将此数组添加到MySQL(很困惑)

mysql - mysql中重复记录的编号(二)

mysql - 获取给定范围内所有日期的结果,包括不存在的日期

html - Laravel 5 正在加载旧的 css

laravel - 单独加载查询结果的关系