0

我需要使用更新数据库 laravel 查询来限制更新的行数。

我试过了,但这将更新所有行并且忽略限制:

DB::table('threads as thr')
->join('replies as rep', 'rep.thread_id', '=', 'thr.id')
->where([
        ['rep.created_at', '<', Carbon::now()->subDays(30)],
        ['thr.closed','=',false]
 ])
 ->limit(10)
 ->update([ 'thr.closed' => true ]);

我需要限制结果更新,而不是改变 where 条件。我什至尝试过Thread::chunk(...),这将遍历块中的结果,但遍历所有块。对于块,我可以使用 return false。但是在调用块函数之后,它将总是从第一个项目再次迭代。例如,在结果中,按 10 分块将始终只迭代前 10 个项目。

可以通过这个“DB::”符号来限制它,还是我需要选择另一种方法?

(我使用 PostgreSQL 和 Laravel DB conn。)

4

2 回答 2

0

修改您的代码,如下所示

DB::table('threads as thr')
->join('replies as rep', 'rep.thread_id', '=', 'thr.id')
->where([
      ['rep.created_at', '<', Carbon::now()->subDays(30)],
      ['thr.closed','=',false]
])
->take(10)->update([ 'thr.closed' => true ]);

于 2019-09-14T08:38:45.050 回答
0

好的,这很好用:

 DB::table("threads")->whereIn('id', function ($query) {
        $query->from('threads as thr')
              ->join('replies as rep', 'rep.thread_id', '=', 'thr.id')
              ->select('thr.id')
              ->where([
                       ['rep.created_at', '<', Carbon::now()->subDays(30)],
                       ['thr.closed','=',false]
                   ])
              ->limit(1);
    })->update([ 'thr.closed' => true ]);

在这里找到答案:Laravel 5 更新单行限制不起作用't-work

于 2019-09-14T09:23:46.447 回答