Laravel模型查询-可以使用“ Models:all()”,但“ where / whereRaw”不返回任何数据

时间:2019-07-07 11:56:37

标签: php laravel orm model

Laravel PHP,

我尝试查询Models以获取json数据,这很奇怪,我只能使用Models:all()之类的查询,而不能使用where。

第一次查询

我可以使用以下查询:

$models = SadaqahHistory::all();

它将返回结果:

{
    "status": 200,
    "message": "Success, user=25, date from=2019-07-01, end date=2019-07-31",
    "data": [
        {
            "id": 1,
            "user_id": 372,
            "month": 7,
            "year": 2019,
            "name": null,
            "point_total": 198,
            "total": 4580,
            "sadaqah_date": "2019-07-05 00:00:00",
            "status": 0,
            "is_dzikir": 0,
            "created_at": null,
            "updated_at": null
        },
        {
            "id": 2,
            "user_id": 1034,
            "month": 7,
            "year": 2019,
            "name": null,
            "point_total": 2,
            "total": 46,
            "sadaqah_date": "2019-07-05 00:00:00",
            "status": 0,
            "is_dzikir": 0,
            "created_at": null,
            "updated_at": null
        },
...

用于第二次查询

我不能使用以下查询,因为它将返回空/无数据:

$models = SadaqahHistory::where('user_id', $user->id) ->whereRaw("DATE_FORMAT(sadaqah_date, '%Y-%m-%d') >= '$startDate' AND '$endDate'") ->actived() ->orderBy('sadaqah_date', 'desc') ->get();

它将不返回任何数据/ null:

{
    "status": 200,
    "message": "Success, user=25, date from=2019-07-01, end date=2019-07-31",
    "data": []
}

===编辑,添加 SadaqahHistory Model

namespace App;
class SadaqahHistory extends BaseModel
{
    const STATUS_CONVERT_FROM_POINT = 1;
    protected $table = 'sadaqah_history';

    protected $fillable = [
        'user_id',
        'name',
        'point_total',
        'total',
        'sadaqah_date',
        'status',
        'is_dzikir',
        'foundation_donate_id',
        'created_at',
        'updated_at',
        'created_by',
        'updated_by',
    ];
    protected $hidden = [
        'foundation_donate_id',
        'created_by',
        'updated_by'
    ];
    protected $casts = [
        'status' => 'int',
        'is_dzikir' => 'int',
        'point_total' => 'int',
        'total' => 'int',
        'user_id' => 'int',
        'foundation_donate_id' => 'int',
    ];
    public function __construct(array $attributes = array())
    {
        parent::__construct($attributes);
    }
    public function foundationDonate()
    {
        return $this->hasOne('\App\FoundationDonate', 'id', 'foundation_donate_id');
    }

任何想法,为什么我的第二个模型查询不起作用?

1 个答案:

答案 0 :(得分:2)

根据此SQL,您需要:

SELECT * FROM sadaqah_history WHERE user_id = 25 AND sadaqah_date BETWEEN '2019-06-01' AND '2019-06-30'

如果$startDate$endDate确实具有YYYY-MM-DD格式,则应使用此格式:

$models = SadaqahHistory::where('user_id', $user->id)
      ->whereRaw("sadaqah_date BETWEEN '$startDate' AND '$endDate'")
      ->orderBy('sadaqah_date', 'desc')
      ->get();