【问题标题】:Laravel how to query a pivot table created_at timestamp equal to a dateLaravel如何查询数据透视表created_at时间戳等于日期
【发布时间】:2018-10-25 15:33:40
【问题描述】:

我有用户和习惯,还有一个 habit_user 表来加入他们。

我是这样查询的:

$track = $h->userAnswers()->where('user_id', Auth::user()->id)->wherePivot('created_at', '=', Carbon\Carbon::now()->subDays($i))->first();

这是一个循环运行,倒计时 7 天。数据库中有一条记录是 created_at: 2018-10-23 04:48:44

在我的习惯模型中,我有你期望的方法:

public function userAnswers()
{
    return $this->belongsToMany('App\Habit', 'habit_user_answers')->withTimestamps()->withPivot('answer_one', 'created_at')->orderBy('pivot_created_at', 'desc');

}

为什么查询不会得到记录?

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    您正在比较日期时间,因此只有当日期和时间相同时,查询才会抛出结果。

    你可以像这样比较日期:

    wherePivot('created_at', '>=', Carbon\Carbon::now()->subDays($i)->startOfDay())->wherePivot('created_at', '<=', Carbon\Carbon::now()->subDays($i)->endOfDay())
    

    【讨论】:

      【解决方案2】:

      首先,我认为您需要考虑 Laravel 关于命名方法和属性的约定。

      我将根据您的结构(包括用户和习惯)假设以下内容。所以,我们有一个User 模型和一个Habit 模型,一个用户belongsToMany habits 和一个习惯belongsToMany users。此外,数据透视表 habit_user 包含额外的字段,如 answer_oneanswer_created_at 和时间戳。

      如果您现在想查询现在的习惯,您有两种解决方案:

      1- 使用 wherePivot()

      auth()->user()->habits()->wherePivot('answer_created_at', today())->get();
      auth()->user()->habits()->wherePivot('answer_one', '!=', 'something')->get();
      

      2- 使用 whereHas()

      auth()->user()->whereHas('habits', function($query){
          $query->where('pivot.answer_one', 'something');
      })->get();
      

      【讨论】:

        猜你喜欢
        • 2019-03-15
        • 1970-01-01
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 2015-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多