【问题标题】:how create a collection of models from array with their IDs - Laravel如何从带有 ID 的数组创建模型集合 - Laravel
【发布时间】:2016-12-17 01:26:12
【问题描述】:

我正在使用按钮 attach (name)' for each model which is not connected to the base model with abelongsToMany` 关系创建一个 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 数组中获取集合

数组按预期创建

我的问题(替代方案)

我实际上想在这里得到的是一组模型,它们没有通过stages() 关系附加到主要的$object

关系定义如下:

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

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

【问题讨论】:

    标签: arrays laravel collections laravel-5.3 hydration


    【解决方案1】:

    您可以使用whereNotIn() 来解决您的问题:

    $attached_stages = $object->stages()->getRelatedIds()->toArray();
    
    $missing_stages = Stage::whereNotIn('id', $attached_stages)->get();
    

    【讨论】:

    • 我也可以多喝点咖啡,看来。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 2016-12-11
    • 2020-07-03
    • 2022-01-20
    • 2016-11-19
    相关资源
    最近更新 更多