[英]Get second highest date from related table
我正在嘗試使用 Eloquent Laravel 6 從關系表中獲取第二高的日期。
MoodTable
id animal_id date mood
1 1 2019-12-14 happy
2 1 2019-12-11 drunk
3 1 2019-12-13 sad
AnimalTable
id name
1 Dog
例如,我希望能夠查詢:“今天狗很高興。之前他喝醉了。
要獲取我使用的最高值:
return $this->hasMany('App\AnimalMood', 'animal_id')->select(DB::raw('
mood,
animal_id,
MAX(date) as max_date,
'))
->groupBy('stock_id');
然而,當談到第二個最高日期時......我出去了......
我看過如何在 SQL 中返回第二條最新記錄? 對於某些答案,但無法將其放入關系場景中,也無法將其翻譯為 Eloquent。
理想情況下,我想從我的控制器運行Animal::with('moodPrevious')->get()
和Animal::find(1)->moodPrevious
...
當您查詢它時,我會更改關系並將所有相關模型獲取到您的Animal
模型。
return $this->hasMany('App\\AnimalMood', 'animal_id');
下面返回情緒預先排序的動物。
$animals = Animal::with(['mood' => function($q){
$q->orderByDesc('date');
}])->get();
Laravel 提供了很多與相關模型配合良好的收集方法。 我會使用你可以提供給first()
的回調來獲得你想要的模型情緒。 您可能已經擁有了您想要的特定模型,無論是通過對上述集合進行 foreach 還是類似的東西。 該關系將是一個collection
實例,因此我們使用集合方法來獲得所需的mood
。
$previousMood = $animal->mood->first(function($value, $key){
return $key == 1 // You can use whatever here, this will return the second item on the relation, or the previous mood.
});
請參閱https://laravel.com/docs/5.8/collections#method-first以獲取參考。
我認為這會奏效
return $this->hasMany('App\AnimalMood', 'animal_id')
->select(
DB::raw('
mood,
animal_id,
MAX(date) as max_date,
')
)
->where(
DB::raw("
date = (
SELECT
MAX(date)
FROM animal_moods
WHERE date < (
SELECT
MAX(date)
FROM
animal_moods
)
)
")
)
->groupBy('stock_id');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.