【问题标题】:Laravel get latest price in a given currencyLaravel 获取给定货币的最新价格
【发布时间】:2015-04-28 15:04:57
【问题描述】:

我有三个模型:

  • 产品
  • 价格
  • 货币

一个产品可以有多个价格(价格根据日期而变化),价格可以是多种货币。

这是示例架构:

产品

|-------------------------------|
| id   | name                   |
|-------------------------------|
| 1    | Hat                    |
| 2    | T-shirt                |
|-------------------------------|

价格

在这里,您可以看到单个产品(帽子)可以有多个价格,以不同的货币表示,每个价格从给定日期开始有效。

在撰写本文时(2015 年 2 月 26 日),产品 1(帽子)的当前价格应为 12 英镑或 11 美元。

|-------------------------------------------------------|
| id   | product_id | currency_id | price | valid_from  |
|-------------------------------------------------------|
| 1    |     1      |    1        | 10    | 2014-01-01  |
| 2    |     1      |    1        | 12    | 2015-01-01  |
| 3    |     1      |    1        | 14    | 2016-01-01  |
| 4    |     1      |    2        | 8     | 2014-01-01  |
| 5    |     1      |    2        | 10    | 2015-01-01  |
| 6    |     1      |    2        | 11    | 2015-02-01  |
|-------------------------------------------------------|

货币

|-------------------------------|
| id   | name                   |
|-------------------------------|
| 1    | GBP                    |
| 2    | USD                    |
|-------------------------------|

我想要做什么

我希望能够以给定货币获得当前价格的所有产品。

我已将模型设置如下:

用户

public function prices()
{
    return $this->hasMany('App\Price', 'product_id', 'id');
}

价格

public function currency()
{
    return $this->belongsTo('App\Currency', 'currency_id', 'id');
}

public function product()
{
    return $this->belongsTo('App\Product', 'product_id', 'cat_id');
}

货币

未定义任何关系。

我的尝试

$products = $this->product->with([
        'prices' => function($query) use ($currency) {

            $query->where('valid_from', '<=', date('Y-m-d'));
            $query->orderBy('valid_from', 'DESC');

                $currency = $this->currency->where('name', strtoupper($currency))->limit(1)->get();
                $query->where('currency_id', $currency[0]->id);


        },
        'prices.currency'
    ])->get();

这很有效,但没有办法只返回一个价格(在 $query 上添加限制不起作用)

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您需要将关系更改为 belongsToMany

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2020-09-29
      • 2015-10-24
      • 2019-09-08
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多