Laravel多对多关联使用attach()时如何禁用时间戳?
attach() in Laravel Many-to-Many Relationships Hey there! Let's work through this issue together. The core problem here is making sure Laravel doesn't try to insert timestamp fields (like created_at/updated_at) when using attach() on your many-to-many relationship—since your gift_user pivot table doesn't include those columns.
Step 1: Confirm Your Custom Pivot Model Setup
You already added public $timestamps = false; to your GiftUser model, but double-check it extends Laravel's Pivot class (not the base Model class) to ensure it behaves as a proper pivot model:
// app/Models/GiftUser.php namespace App\Models; use Illuminate\Database\Eloquent\Relations\Pivot; class GiftUser extends Pivot { public $timestamps = false; protected $table = 'gift_user'; // Optional, but explicit is better for clarity }
Step 2: Link Your Relationship to the Custom Pivot
The most common oversight here is forgetting to connect your many-to-many relationship to your custom pivot model. If you skip this, Laravel uses a default pivot instance that won't respect your $timestamps = false setting.
Update the gifts() relationship in your User model (and repeat for the users() relationship in the Gift model if needed):
// app/Models/User.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { public function gifts() { return $this->belongsToMany(Gift::class) ->using(GiftUser::class) // Tie the relationship to your custom pivot ->withPivot('count'); // Include your extra pivot column } }
Step 3: Fix a Small Bug in Your updateExistingPivot Call
I spotted a tiny error in your code: the first parameter of updateExistingPivot needs to be the gift's ID, not the entire $gift array. Here's the corrected snippet:
foreach ($all_gifts as $key => $gift) { $gift_user = GiftUser::where('gift_id', $gift['id'])->where('user_id', $user->id)->first(); if(empty($gift_user)){ $user->gifts()->attach($gift['id'], ['count' => 1]); }else{ // Use $gift['id'] instead of $gift here $user->gifts()->updateExistingPivot($gift['id'], ['count' => ($gift_user->count + 1)]); } }
Why This Works
By linking your relationship to the custom GiftUser pivot model (which disables timestamps), Laravel will skip any attempts to insert or update timestamp fields when you call attach() or updateExistingPivot(). This aligns perfectly with your pivot table's structure.
内容的提问来源于stack exchange,提问作者ronrun

