I have two Model named Position and Event, they have many-to-many relationship with each other.
<?php
class Event extends Model
{
protected $fillable = [
'name', 'opta_id'
];
public function positions() {
return $this->belongsToMany(Position::class);
}
}
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?
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.