I seem to have a problem with timestamps - when trying to attach User to Lectures via favorites pivot table - none of the dates updates.

以下是我的迁移:

Schema::create('favorites', function (Blueprint $table) {

    $table->integer('lecture_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();

    $table->primary(['lecture_id', 'user_id']);

});

讲座关系:

public function favorites()
{
    return $this->belongsToMany(User::class, 'favorites');
}

用户关系:

public function favorites()
{
    return $this->belongsToMany(Lecture::class, 'favorites')
                ->withTimestamps();
}

每当我附上:

$event->lecture->favorites()->attach($this->user->id);

Both fields created_at and updated_at are set to 0000-00-00 00:00:00

知道我做错了什么吗?

推荐答案

In order to attach the timestamps to each of the model relationships you need to chain the method ->withTimestamps().

So, for exam, in your case, it would be the following:

public function favorites()
{
    return $this->belongsToMany(User::class, 'favorites')->withTimestamps(); 
}

This would then attach the timestamps. Hope this helps you.

Laravel相关问答推荐

Nginx上带有SSL的Laravel混响

Laravel FAKER语法

使用枢轴插入多对多时的Laravel问题

Laravel查询多对多关系

Laravel 连接表

Laravel:使用 Input::old 时 textarea 不会重新填充

Laravel 错误ReflectionException-类 App\Http\Kernel 不存在

覆盖 HTTP 标头的默认设置 (X-FRAME-OPTIONS)

如何在 laravel 中安装 PHPExcel 库?

无法安装 Laravel 包 - 干预图像

在 Laravel 中无效后防止重定向到主页

如何从 Laravel 中的 hasMany() 关系中获取所有结果?

如何在中间件 Laravel 中获取请求的控制器和操作的名称

CRON 作业(job) - LARAVEL - 输出

如何访问 Carbon 对象类型?

验证匹配字符串

测试指向外部站点的重定向链接

使用 Laravel 将两个模型合并到一个分页查询中,并带有Eager加载的关系

如何在 Laravel 中使用补丁请求?

如何在 Laravel 5 中验证 RESTful API?