首页 > 解决方案 > 我如何从 laravel 中的两个表中获取记录或如何将日期与第二个表匹配

问题描述

我正在尝试从 Laravel 中已链接到另一个表的表中获取记录

表名 1:ProductStock 表名 2:Sales 使用 user_id 列链接到表名 2。

我想从产品库存表和销售额中获取以下记录

->whereBetween('created_at', array($thirdweekdata, $fourthweekdata))



          //I have tried this but it only get from ProductStock table..but I want this 
         wherebetween to be from sales table

         $fourth =  ProductStock::where('status',1)
          ->whereBetween('created_at', array($thirdweekdata, $fourthweekdata))
         ->get();

标签: laravellaravel-5eloquent

解决方案


如果您有salesProductStock 模型中命名的关系方法:

    public function sales()
    {
        return $this->hasMany(\App\Sale::class);
    }

使用with闭包,它将返回 product_stocks 及其在$thirdweekdata和之间的销售额$fourthweekdata

ProductStock::where('status', 1)
            ->whereBetween('created_at', array($thirdweekdata, $fourthweekdata))
            ->with(['sales' => function($query) use ($thirdweekdata, $fourthweekdata) {
               $query->whereBetween('created_at', array($thirdweekdata, $fourthweekdata));
            }])->get();

推荐阅读