vendredi 14 décembre 2018

How update or insert if not exist pivot morph table?

I need add serial number to pivot table and this is morph relations. It should be simple to create pivot table and set as morph table:

class with pivot table name SerialNumber

public function serial_numberable() {
    return $this->morphTo();
}

Now if i want add to this table some data i should create function in other class.

class UsedProducts

public function serialNumbers() {
    return $this->morphMany('App\SerialNumber', 'serial_numberable');
}

the same for other class class UsedKit

public function serialNumbers() {
    return $this->morphMany('App\SerialNumber', 'serial_numberable');
}

The same functions. Now if i wanna add record to pivot table i can use

$usedProduct = UsedProduct::find($productId);

// Add serial numbers
$serialNumber = new SerialNumber;
$serialNumber->serial_no = '87324y8743784';

$usedProduct->serialNumbers()->save($serialNumber);

This morph relations works perfect. But I do not know how to update serial number if record in pivot table exist ? when i tried always is save new records instead of update.

this is my pivot table. enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire