首页 > 解决方案 > 使用日期助手指定月份或 Laravel/Eloquent 问题?

问题描述

我在这个问题上做了一些搜索,并继续被难住。我不确定这是 date() 问题,还是 laravel/eloquent 问题。

背景:

我有三张桌子。一个“医生”表与“患者”表具有来回的 belongsToMany 关系。然后是属于“患者”的“处方”表。在 Doctor 模型上,我创建了从医生表到处方的快捷方式:

public function prescriptions() {
    $this->load(['patients.prescriptions' => function($query) use (&$relation) {
        $relation = $query;
    }]);

    return $relation;
}

我想要实现的是计算日期 - 在当前月份 - 在处方表的“prescribe_date”列中出现的次数。因此,如果医生在 8 月发送了 10 个处方,在 9 月发送了 5 个处方,它应该显示 5(因为我们目前是在 9 月份)。

这是我的仪表板的样子:

$user = Auth::user();
$doctors = User::find(Auth::user()->id)->doctors()->orderBy('full_name', 'asc')->paginate(10);
return view('dashboard')->withDoctors($doctors);

这是我的dashboard.blade.php:

<table class="table table-hover table-sm">
  <thead>
    <tr>
      <th scope="col">Doctor Name</th>
      <th scope="col">Total Patients</th>
      <th scope="col">Monthly Prescriptions</th>
      <th scope="col">Date Doctor Added</th>
    </tr>
  </thead>
  <tbody>
    @foreach ($doctors as $doctor)
      <tr>
        <th scope="row">
          <a href="{{route('doctors.show', $doctor->id)}}">{{$doctor->full_name}}</a>
        </th>
        <td>{{$doctor->patients()->count()}}</td>

        // This is where I'm falling down
        <td>{{$doctor->prescriptions()->where(date('m', strtotime($doctor->prescriptions()->prescribe_date)), '9')->count()}}</td>

        <td>{{date('m-d-Y', strtotime($doctor->created_at))}}</td>
      </tr>
    @endforeach
  </tbody>
</table>

这是它返回的错误:

Undefined property:         
Illuminate\Database\Eloquent\Relations\HasMany::$prescribe_date 

但是,如果我更改此行以反映真正的日期匹配,它将返回正确的计数:

{{$doctor->prescriptions()->where('prescribe_date', '1969-12-31')->count()}}

所以我不确定这是我的 php date() 函数的问题,还是我的 laravel/eloquent 语法的问题,或者与数据库关系有关。谢谢!

更新

我正在尝试使用 where 函数中的 date() 函数从“prescribe”日期列中提取当前月份,然后使用“9”作为当前实际月份的模拟。

标签: phplaraveleloquent

解决方案


您使用的where功能不正确。

where(date('m', strtotime($doctor->prescriptions()->prescribe_date)), '9')

应该是这样的:

where('column_name or key_name' , $value_that_youre_looking_for)

推荐阅读