php - 使用日期助手指定月份或 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”作为当前实际月份的模拟。
解决方案
您使用的where
功能不正确。
where(date('m', strtotime($doctor->prescriptions()->prescribe_date)), '9')
应该是这样的:
where('column_name or key_name' , $value_that_youre_looking_for)
推荐阅读
- javascript - 谷歌地图:未捕获的参考错误:谷歌未定义
- spring - 在 Spring Boot 2.x 中设置 @Bean 属性的更声明性、更简洁的方式?
- struct - 是否可以在 Rust 中将元组定义为结构的成员?
- xml - 使用带有 Python 的 href 链接递归下载 XML 页面
- ios - 以编程方式恢复购买 swift 4
- python - botbuilder-python 对话和对话流
- java - 在正确的窗口中创建 GUI
- c# - C#结构推荐
- java - 使用带有 BlockingQueue 的构造函数创建的 ThreadPoolExecutor 如何
作为参数,将 Callables 加入队列? - c - 链表内存问题