【问题标题】:Laravel Query Item from table with selected relationships from another tableLaravel 查询表中的项目与另一个表中的选定关系
【发布时间】:2020-10-30 22:02:21
【问题描述】:

有两个相关的表 - Product 和 SalesForecast。我想查询某个供应商的产品以及某个时期的销售预测。

建立关系。我的查询如下:

$products = Product::where('supplier_id', $supplier)
    ->whereHas('stock_forecasts_fk', function ($query) use ($begin, $end) {
        $query->whereDate('date', '>', $begin);
        $query->whereDate('date', '<', $end);
    })
    ->get();

产品模型中的关系如下:

public function stock_forecasts_fk()
{
    return $this->hasMany('App\Models\StockForecast');
}

此查询不能 100% 工作。我希望该供应商的所有产品都来(无论他们是否有预测)。如果他们有预测,我只需要那个时期的预测。否则,该产品将没有,预测。但是所有产品都需要来。有人可以建议如何修复此查询,结果如下:

供应商的所有产品都带有开始和结束日期之间的相关预测。如果没有预测,那么产品可以没有预测。

【问题讨论】:

  • 我的理解是正确的,您总是想要属于该供应商的所有产品,但只加载相关的 StockForecasts?
  • 没错。

标签: laravel eloquent


【解决方案1】:

您必须使用预先加载的关系进行查询。使用whereHas,只会收集匹配的相关价值产品。使用with闭包查询相关表

$products = Product::with(['stock_forecasts_fk' => function($query) {
    $query->whereDate('date', '>', $begin)
        ->whereDate('date', '<', $end);
}])
->where('supplier_id', $supplier)
->get();

【讨论】:

    【解决方案2】:

    您可以使用 with 并将带有您的条件的闭包传递给它:

    $products = Product::where('supplier_id', $supplier)
        ->with(['stock_forecasts_fk' => function ($query) use ($begin, $end) {
            $query->whereDate('date', '>', $begin)
                ->whereDate('date', '<', $end);
        }])
        ->get();
    

    来自docs

    约束急切负载

    有时您可能希望预先加载关系,但还需要指定 急切加载查询的附加查询条件。这是一个 示例:

    $users = App\Models\User::with(['posts' => function ($query) {
        $query->where('title', 'like', '%first%');
    }])->get();
    

    在这个例子中,Eloquent 只会预先加载帖子所在位置的帖子 标题列包含单词first

    【讨论】:

      【解决方案3】:

      来自我阅读过的文档here

      whereHas 只包含具有 stock_forecasts_fk 的 Product,而丢弃没有 stock_forecasts_fk 的 Product。

      要选择所有产品,无论它有 stock_forecasts_fk,你应该使用with

      $products = Product::where('supplier_id', $supplier)
          ->with([
              'stock_forecasts_fk' => function ($query) use ($begin, $end) {
                  $query->whereDate('date', '>', $begin);
                  $query->whereDate('date', '<', $end);
              }
          ])
          ->get();
      

      【讨论】:

        猜你喜欢
        • 2018-09-08
        • 1970-01-01
        • 2020-12-10
        • 1970-01-01
        • 2015-01-02
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        相关资源
        最近更新 更多