我有两个名为Position和Event的模型,它们彼此之间具有多对多关系。
<?php
class Event extends Model
{
protected $fillable = [
'name', 'opta_id'
];
public function positions() {
return $this->belongsToMany(Position::class);
}
}
Run Code Online (Sandbox Code Playgroud)
class Position extends Model
{
protected $fillable = [
'name', 'short_name'
];
public function events() {
return $this->belongsToMany(Event::class);
}
}
Run Code Online (Sandbox Code Playgroud)
每个数据库中的event
每个position
数据库都应有一个透视条目,没有例外。因此,每当用户创建一个新event
条目时,我都希望为每个现有条目创建一个透视条目position
。
我正在努力使用文档和SO来解决这个问题。我可以通过显式命名db中所有位置的ID来使用sync()或attach()进行连接。在EventController
的store
方法中:
$data = $request->all();
$event = Event::create($data);
$event->positions()->sync([1, 22, 34, 167]);
Run Code Online (Sandbox Code Playgroud)
但是,要使此方法起作用,我首先必须从positions
表中获取所有条目,将它们格式化为ID数组,然后将它们传递给此方法。有任何内置或规范的方法可以做到这一点吗?