Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

webcodecs's avatar

Strange query on updateOrCreate

Hey guys, im using updateOrCreate to update a pivot table with a mass of entries. The queries that will be executed are wrong and i have no idea where it comes from. Maybe some of you have an idea.

The pivot table looks like:

  • customer_id
  • store_id
  • role_id
  • last_populate_at

I have an unique index on the three columns customer_id, store_id, role_id (customer_store_customer_id_store_id_role_id_unique)

My call to updateOrCreate values is:

CustomerStore::updateOrCreate([
                'customer_id' => $customer->id,
                'store_id'    => $store->id,
                'role_id'     => $store->role_id,
            ],
            [
                'last_populate_at' => $now,
            ]);

This call executes the following query:

update customer_store set last_populate_at = 2022-11-09 14:10:14 where '' = 98 and '' = 98

I cant figure at where it comes from and hope you can give me a hint.

regards

0 likes
8 replies
tykus's avatar

What does the CustomerStore model look like?

webcodecs's avatar

@tykus

class CustomerStore extends Pivot
{
    public $timestamps = false;

    protected $table = 'customer_store';
}
webcodecs's avatar

Is it wrong to use updateorCreate and the correct approach is to use updateOrInsert?

tykus's avatar

@webcodecs well, the "correct" approach for a many-to-many relationship is a sync or attach.

webcodecs's avatar

@tykus Yes but i need to sync withPivot and without detaching. I did not find a method covering that.

cwhite's avatar

@webcodecs,

The signature for syncWithPivotValues() is:

public function syncWithPivotValues($ids, array $values, bool $detaching = true)

Therefore you should be able to use

->syncWithPivotValues([<ids>], [<pivot_values>], detaching: false)

1 like
tykus's avatar
tykus
Best Answer
Level 104

@webcodecs syncWithoutDetaching takes the additional attributes:

$customer->stores()->syncWithoutDetaching([
	$store->id => ['role_id' => $store->role_id, 'last_populate_at' => $now]
]);
1 like
webcodecs's avatar

Thanks for your help! I must have missed it before.

Please or to participate in this conversation.