laravel - 我如何从 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();
解决方案
如果您有sales
ProductStock 模型中命名的关系方法:
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();
推荐阅读
- clickhouse - ClickHouse 新手,无法创建本地主机
- c# - 找不到类型或命名空间名称“SpecialEffects”
- git - 从主干合并到分支,但只合并分支中的文件
- vue.js - 如何手动处理下拉可见性而不是 Vuetify 控制这个
- powershell - 身份引用 ACL 前的问号?
- git - 用户如何能够在不授予他访问权限的情况下推送 bitbucket 私人帐户?
- cpu-usage - 使用 spdlog 以异步模式登录时,如何设置 spdlog 正在使用的线程的 cpu 亲和性?
- c# - 如何将文件写入UWP c#中的应用程序根目录
- c# - 使用 ClickOne 安装后保护用户文件
- package.json - npm 错误!在以下 package.json 文件的窗口命令行上运行“npn start”时,正在显示代码 ELIFECYCLE