我有一个模型,其中包含多个。每个属于一个。
我对这个应该怎么工作感到困惑。区域已经存在,我只需要将它们与所关联的销售区域建立联系。
class SalesArea extends Model
{
public function regions() {
return $this->hasMany('App\Region');
}
}
class Region extends Model
{
public function sales_area() {
return $this->belongsTo('App\SalesArea');
}
}
由于组织结构的一些变化,在创建区域之后才会创建父级(销售区)。我试图在创建销售区记录时将区域与其关联的销售区相关联。
我创建了一个迁移来将 sales_area_id 添加到 "regions" 表中,并且它们当前都是空的。
我有一个选择框,其中包含不同区域的 ID,并且我希望通过 ID 数组一次性将这些区域与销售区关联起来。但是,没有任何关联方法能够起作用。
$area = SalesArea::create($request->all());
$area->regions()->attach([1,2,3]); // BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::attach()
$area->regions()->add([1,2,3]); // BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::add()'
$area->regions()->sync([1,2,3]); // BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::sync()'
$area->regions()->associate([1,2,3]); // BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::associate()'
我对这个应该怎么工作感到困惑。区域已经存在,我只需要将它们与所关联的销售区域建立联系。
attach()
、sync()
和associate()
与“belongs to many”关系有关。你不能在这里使用它们。 - iamab.inRegion::whereIn('id', [$ids])->update(['sales_area_id' => $area->id]);
? - DevonRegion::where('id', [array of IDs]);
不会返回Region
的集合,而是一个QueryBuilder
,所以在->saveMany()
中使用它不会有太大作用。必须先使用->get()
。是的,我确定有一种避免循环的方法,但这只是一个例子。 - Tim Lewis