I seem to have a problem with timestamps - when trying to attach User
to Lectures
via favorites
pivot table - none of the dates updates.
Here's my migration:
Schema::create('favorites', function (Blueprint $table) {
$table->integer('lecture_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->primary(['lecture_id', 'user_id']);
});
Lecture relationship:
public function favorites()
{
return $this->belongsToMany(User::class, 'favorites');
}
User relationship:
public function favorites()
{
return $this->belongsToMany(Lecture::class, 'favorites')
->withTimestamps();
}
Whenever I attach:
$event->lecture->favorites()->attach($this->user->id);
Both fields created_at
and updated_at
are set to 0000-00-00 00:00:00
Any idea what I might be doing wrong?
The attach function only adds records to the Pivot table. The sync function replaces the current records with the new records. This is very useful for updating a model.
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function. Think of it like this: when you don't exactly know what a query will return then you need to use get() .
You either have to declare public $timestamps = false; in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With