laravel - 尝试在 Laravel Eloquent 中使用 whereBetween 进行搜索时出现问题
问题描述
我在下面的 MySQL 中有 2 个数据库表。
表格1
CREATE TABLE `tblaccount` (
`account_id` mediumint(8) UNSIGNED NOT NULL,
`account_number` varchar(100)
)
ALTER TABLE `tblaccount`
ADD PRIMARY KEY (`account_id`);
表 - 2
CREATE TABLE `tblcollectoractions` (
`collector_action_id` mediumint(8) UNSIGNED NOT NULL,
`account_id` mediumint(8) UNSIGNED DEFAULT NULL,
`pay_date` date DEFAULT NULL
);
ALTER TABLE `tblcollectoractions`
ADD PRIMARY KEY (`collector_action_id`),
ADD KEY `tblcollectoractions_account_id_foreign` (`account_id`);
我在下面有一个查询。它根据 account_id 连接两个表中的记录。它还过滤 tblcollectoractions 表中 pay_date 位于开始日期和结束日期之间的那些帐户。
这是我的 Laravel Eloquent 查询。AccountModel 与 tblaccount 相关,ActionModel 与 tblcollectoractions 相关。
$query = (new AccountModel())->newQuery();
$data->whereIn("account_id", function($query) use($inputs) {
$query->select('account_id')->from(with(new ActionModel)->getTable())
->whereBetween('pay_date', [$inputs["from_pay_date"], $inputs["to_pay_date"]]);
});
但是,这显示了表 tblcollectoractions 中的所有记录。我的意思是,它不会根据开始和结束日期进行过滤。
我错过了什么吗?
解决方案
这是最有说服力的方法,检查是否设置了 $inputs 变量
$data = AccountModel::query()
->with([
'actions' => function($query) use ($inputs) {
if ($inputs['from_pay_date']) {
$query->whereBetween('pay_date', [
$inputs['from_pay_date'],
$inputs['to_pay_date']
]);
}
}
])
->has('actions')
->get();
模型应如下所示:
AccountModel.php
class AccountModel extends Model
{
protected $guarded = ['id'];
public function actions()
{
return $this->hasMany(ActionModel::class, 'account_id', 'account_id');
}
}
推荐阅读
- database - PL/SQL 中的 mod() 返回一个意外的值
- node.js - Mongoose $lookup 计数引用
- javascript - 当角度应用程序中达到最大长度时如何防止输入字段上的其他字符
- haskell - eDSL - 实现一个只能在序列中使用一次的动作
- python - 过滤引号内的 df 值
- c++ - GLSL 1.3 逆 4x4 矩阵
- string - 如何分析字符串?
- c# - 使用 ajax 传递给 ASP.NET Core Controller 的参数始终为 null
- python-3.x - 在 Python 3 中 random.shuffle 非常慢,带有列表
- c# - 功能不是每次都运行