首页 > 解决方案 > 尝试在 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 中的所有记录。我的意思是,它不会根据开始和结束日期进行过滤。

我错过了什么吗?

标签: laravellaravel-6laravel-6.2

解决方案


这是最有说服力的方法,检查是否设置了 $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');
    }
}

推荐阅读