雄辩的关系枢轴表与表

时间:2015-10-27 15:32:07

标签: php laravel eloquent relationship

我阅读了laravel文档但我无法理解。 我在我的数据库上有这个结构。

PriceTable - 其中包含有关促销价格和默认价格的信息。

产品 - 包含有关产品的信息。

和PriceTable_Product - 包含Product和PriceTable的外键以及相应的价格。

示例:

PriceTable        |  PriceTable_Product                 |  Product
id |  description |  PriceTable_id | Product_id | price |  product_id| name  
1  |  default     |    1           |    1       | 5.00  |   1        | test
2  |  promotional |    2           |    1       | 3.50  |

在Order表中我可以有多个产品,所以我想知道是否可以将Order表与数据透视表PriceTable_Product关联起来,因为我需要在产品售出时哪个表属于价格的信息

感谢。

1 个答案:

答案 0 :(得分:0)

首先,您可以定义Product和PriceTable之间的关系。

产品型号(App \ Product.php)

<?php

namespace App;

class Product extends Model {
    protected $table = 'products';
    //if the default primary key isn't 'id' you may use $primaryKey
    protected $primaryKey = 'product_id';
    public function pricetables() {
        return $this->belongsToMany('App\PriceTable');
    }
}

PriceTable模型(App \ PriceTable.php)

<?php

namespace App;

class PriceTable extends Model {
    protected $table = 'pricetable';
    public function products() {
        return $this->belongsToMany('App\Product');
    }
}

如果你创建了关系,那么你可以使用:

$product = App\Product::find(1);

foreach ($product->pricetables as $pricetable) {
    echo $pricetable->pivot->description;
}
相关问题