【问题标题】:Laravel 5.1 eloquent::attach() method with timestamps带有时间戳的 Laravel 5.1 eloquent::attach() 方法
【发布时间】:2016-02-17 20:45:42
【问题描述】:

我的时间戳似乎有问题 - 尝试通过 favorites 数据透视表将 User 附加到 Lectures 时 - 没有任何日期更新。

这是我的迁移:

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);

created_atupdated_at 两个字段都设置为 0000-00-00 00:00:00

知道我做错了什么吗?

【问题讨论】:

  • 在您的belongsToMany 中您是否尝试过与->withTimestamps(); 链接所以..$this->belongsToMany(User::class, 'favourites')->withTimestamps();
  • 你说得对——我在User 上做过,但在Lecture 上忘记了。非常感谢@Phorce - 您可以将其发布为答案以便我接受吗?
  • @Phorce,发布您的信息作为答案,未来的读者将从中受益:-)
  • @seb 完成了这个:) 如果你满意,你能把它标记为接受的答案吗?

标签: laravel eloquent laravel-5.1


【解决方案1】:

为了将时间戳附加到每个模型关系,您需要链接方法->withTimestamps()

所以,对于考试,你的情况如下:

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

这将附加时间戳。希望对您有所帮助。

【讨论】:

  • 非常感谢@Phorce!
猜你喜欢
  • 2020-11-09
  • 2017-05-12
  • 2015-09-17
  • 2013-11-25
  • 2015-12-17
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 2018-10-13
相关资源
最近更新 更多