R
R
Rumus Bin2017-11-25 22:45:24
ORM
Rumus Bin, 2017-11-25 22:45:24

How to synchronize the hasMany relationship model in Laravel as sync?

Good time everyone. I can not solve the problem with editing a contact and his phone numbers.
There are two contact models

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    protected $table = 'contacts';
    public function phoneNums()
    {
        return $this->hasMany('App\Models\PhoneNum');
    }
}

and PhoneNum model
class PhoneNum extends Model
{
    protected $table = 'phoneNums';
    protected $fillable = ['phone_num'];

    public function contact()
    {
        return $this->belongsTo('App\Models\Contact');
    }
}

When editing a contact, a contact name and an array of phone numbers "arrive" from the form to the Controller method, they can be either previously owned by this contact or new ones, and their number can be different (more or less than the original one)
ContactController
public function update(Request $request, $id)
    {
        $contact = Contact::find($id);
        $contact->name = $request->name;
        $contact->save();
        
      // what should I do with the array $request->phonenumber ????

        return redirect('/');
    }

And now I’m completely confused and don’t know how to synchronize new bodies. numbers.
Really need some good advice! Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vism, 2017-11-26
@vism

I did hardcore
Deleted - added

$contact->phoneNums()->delete();
foreach(...){
//добавляем из массива
}

Well, if you do it right.
Then you collect existing IDs from the input
Do a search by numbers notIn IDs from the
input Delete them and
add those that remain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question