Laravel 手动更新时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35354818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:13:59  来源:igfitidea点击:

Laravel Manual Update Timestamp

laravel

提问by Matt Pierce

I have a miscellaneous database table that is updated each time a user visits another user's profile. I'm having trouble creating a manual timestamp column though. Since I didn't create a model for this, I'm doing it manually which shouldn't be an issue because this database isn't accepting any user-generated input.

我有一个杂项数据库表,每次用户访问另一个用户的个人资料时都会更新该表。但是,我在创建手动时间戳列时遇到了麻烦。由于我没有为此创建模型,因此我是手动进行的,这应该不是问题,因为该数据库不接受任何用户生成的输入。

Migration:

移民:

public function up()
{
    Schema::create('recently_visited', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('visitor_id');
        $table->integer('profile_id');
        $table->integer('times_visited');
        $table->timestamp('last_visit');
    });
}

Controller:

控制器:

$visits = DB::table('recently_visited')
    ->where('profile_id',$user->id)
    ->where('visitor_id',Auth::user()->id)
    ->increment('times_visited')
    ->update(array('last_visit' => Carbon::now()));

I get the following error. Please help me understand, what is the integer this is being called on. Thanks!

我收到以下错误。请帮助我理解,这个被调用的整数是什么。谢谢!

Fatal error: Call to a member function update() on integer

致命错误:在整数上调用成员函数 update()

ANSWER:

回答:

I just needed to include all my updated within the increment() in the query builder.

我只需要在查询构建器的 increment() 中包含我的所有更新。

$visits = DB::table('recently_visited')
    ->where('profile_id',$user->id)
    ->where('visitor_id',Auth::user()->id)
    ->increment('times_visited', 1, ['last_visit' => Carbon::now()]);

回答by peterm

Please help me understand, what is the integer this is being called on.

请帮助我理解,这个被调用的整数是什么。

increment()method doesn't return query builder instance but rather updates the record itself and returns an integer.

increment()方法不返回查询构建器实例,而是更新记录本身并返回一个整数。

You should be able to do this:

你应该能够做到这一点:

$visits = DB::table('recently_visited')
    ->where('profile_id',$user->id)
    ->where('visitor_id',Auth::user()->id)
    ->increment('times_visited', 1, array('last_visit' => Carbon::now()));