2

I have two Model named Position and Event, they have many-to-many relationship with each other.

  • Event:
<?php

class Event extends Model
{
    protected $fillable = [
        'name', 'opta_id'
    ];

    public function positions() {
        return $this->belongsToMany(Position::class);
    }
}
  • Position:
class Position extends Model
{
    protected $fillable = [
        'name', 'short_name'
    ];

    public function events() {
        return $this->belongsToMany(Event::class);
    }
}

Each event should have a pivot entry for each position currently in the database, there are no exceptions. So every time a user creates a new event, I want to create a pivot entry for each existing position.

I am struggling to figure this out using the documentation and SO. I could use sync() or attach() to make the connections by explicitly naming the IDs of all the positions in the db. In the EventController's store method:

$data = $request->all();
$event = Event::create($data);
$event->positions()->sync([1, 22, 34, 167]);

But for this to work, I would first have to get all the entries from the positions table, format them into an array of IDs, and pass them to this method. Is there any built-in or canonical way to do this?

sveti petar
  • 3,637
  • 13
  • 67
  • 144

2 Answers2

8

There is no built-in way, but the manual solution is quite short:

$event->positions()->attach(Position::pluck('id'));

attach() is more efficient than sync() because it inserts all pivot records in a single query.

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
0

I've gotten the other solution, So to may achieve your purpose you have

// the 1st sync will remove all the relationship to the position table
$event->positions()->sync([1, 22, 34, 167]);
// the 2nd sync is to extend the relationship from the 1st
$event->positions()->syncWithoutDetaching([1, 22, 34, 167]);
ABDO
  • 130
  • 1
  • 6