【问题标题】:Laravel - latest() chained with where() behaviorLaravel - latest() 与 where() 行为链接
【发布时间】:2022-12-09 04:11:17
【问题描述】:

所以我有一个包含 created_at 和外键 student_id 和 status_id 的多对多表。

对于每个学生,我只想在最新的一个有 status_id = 1 的情况下检索一个条目。

我这样试过:(这是一个查询链,在这种情况下 $query 将是 Student::where(something else))

$query->whereHas('statusuri', function($query) use ($statusuri) {
                $query->latest('status_student.created_at')->where('status_id', 1);
});

(statusuri 是多对多关系)

但我得到的结果与我需要的不同。

它首先执行 where 子句,然后执行 latest()。基本上,它检索与 where 匹配的最后一个条目。

我想搜索每个学生,最新条目,如果 where 子句匹配,则获取该条目。如果没有,请不要返回任何东西。

Eloquent 可以做到吗?

谢谢。

【问题讨论】:

  • 尝试将 latest 移出闭包
  • 你介意展示你的想法吗?

标签: php laravel eloquent


【解决方案1】:

您是否考虑过“拥有众多”关系:https://laravel.com/docs/9.x/eloquent-relationships#advanced-has-one-of-many-relationships

您可以在 Student 模型中建立关系:

public function latestStatus()
{
    return $this->hasOne(StatusStudent::class)->ofMany([
        'created_at' => 'max',
        'id' => 'max',
    ], function ($query) {
        $query->where('status_id', 1);
    });
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2016-08-13
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多