如何从数组及其 ID 创建模型集合 - Laravel

问题描述 投票:0回答:1

我正在使用按钮

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
方法对我不起作用。集合中没有任何内容被删除。

任何帮助表示赞赏。谢谢。

php arrays laravel laravel-5 collections
1个回答
1
投票

您可以使用

whereNotIn()
来解决您的问题:

$attached_stages = $object->stages()->getRelatedIds()->toArray();

$missing_stages = Stage::whereNotIn('id', $attached_stages)->get();
© www.soinside.com 2019 - 2024. All rights reserved.