我正在创建一个带有按钮attach (name)' for each model which is not connected to the base model with a
belongsToMany` 关系的 foreach 循环。
我有一个带有特定模型 ID 的数组
$attached_stages = $object->stages()->getRelatedIds()->toArray(); // output: 1, 2
然后我有同一个模型的所有模型实例,
$all_stages = Stage::orderBy('id', 'asc')->pluck('id')->all(); // output: 1,2,3,4 ... 6
$missing_stages = array_diff($all_stages, $attached_stages); // output: 3,4,5,6
我的问题:如何从$missing_stages
数组中获取集合
数组按预期创建
我的问题(替代解决方案)
我实际上想在这里得到的是一组模型,这些模型没有通过关系附加到主$object
模型stages()
。
该关系定义如下:
public function stages()
{
return $this->belongsToMany('App\Models\Stage', 'lead_stage', 'lead_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}
我无法使用此代码获得我想要的收藏:
$all_stages = Stage::get(); // output: collction 1,2,.... 6
$attached_stages = $object->stages(); // output: 1, 2
$missing_stages = $all_stages->diff($attached_stages); // expected output: 3,4,5,6
注意:我试图删除关系定义中的枢轴部分,但没有帮助,该diff
方法对我不起作用。收藏中没有任何内容。
任何帮助表示赞赏。谢谢。