如何使用上一次和下一次最大值获得模型的属性值?
假设我有一个user
模型,其中有一个age
列。我现在想知道用户x
的年龄以及最近的以前和以后的年龄值。
$age = User::find($id)
发布于 2022-10-27 11:13:47
在您发布的代码中,$age
当前是一个User
实例,即null
,所以这并不能起到很大作用。
如果age
是users
表中的一个列,那么您可以这样做:
$age = User::findOrFail($id)->age;
try {
return User::where('age', '<', $age)
->orderBy('age', 'DESC')
->firstOrFail()
->age;
} catch (ModelNotFoundException $mnfe) {
return null; // Or similar
}
try {
return User::where('age', '>', $age)
->orderBy('age', 'ASC')
->firstOrFail()
->age;
} catch (ModelNotFoundException $mnfe) {
return null; // Or similar
}
使用$age
(让我们设想30)作为参考点:
小
- Query for anyone younger (`'age' < 30`)
- Ordering them from 29 to 0 (`DESC`)
- Find the first one (or failing if there are none)
- Return that User's `age`
老年
- Query for anyone older (`'age' > 30`)
- Ordering them from 30 to ∞ (`ASC`)
- Find the first one (or failing if there are none)
- Return that User's `age`
Sidenote,这段代码可以作为诸如getPreviousAge($age)
、getNextAge($age)
等函数在Controller或Model中运行。
https://stackoverflow.com/questions/74227038
复制