在创建时附加到从多对多方法的所有可能的关系



我有两个模型,名为"位置"和"事件",它们彼此之间具有多对多关系。

  • 事件:
<?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);
    }
}

每个event都应该为数据库中当前position都有一个透视条目,没有例外。所以每次用户创建新event时,我都想为每个现有的position创建一个透视条目。

我正在努力使用文档和 SO 来解决这个问题。我可以使用sync((或attach((通过显式命名数据库中所有位置的ID来建立连接。在EventControllerstore方法中:

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

但是要使其正常工作,我首先必须从positions表中获取所有条目,将它们格式化为 ID 数组,然后将它们传递给此方法。是否有任何内置或规范的方法可以做到这一点?

没有内置的方法,但手动解决方案很短:

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

attach()sync()更有效,因为它在单个查询中插入所有透视记录。

我得到了另一个解决方案,所以为了达到你的目的,你有

// 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]);

最新更新