代码之家  ›  专栏  ›  技术社区  ›  William Turrell

很多人都有

  •  0
  • William Turrell  · 技术社区  · 7 年前

    AdInterest->groups  
    AdInterestGroup->interests
    

    我可以在一个群体中找到所有的“兴趣”,比如:

    $interests = AdInterestGroup::find(1)->interests->pluck('foo');
    

    我需要的是来自多个组的相关“foo”字段的合并、重复数据消除数组。
    ->unique() ,但首先,正如你所料,这:

    AdInterestGroup::whereIn('id',[1,2])->interests->get();
    

    投掷:

    属性(兴趣)不存在于雄辩的生成器实例中。

    这个建议似乎有用 急装 通过 使用()

    AdInterestGroup::with('interests')->whereIn('id',[1,2])->get();
    

    首先,正如您所期望的那样,这给了我一个包含两个值的数组(每个ID一个值)。

    还有,如果我试着 pluck('foo') 同样,它在错误的数据库表中查找:从 表,而不是关系( 非利息 ).

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jonas Staudenmeir    7 年前

    使用 pluck() flatten() :

    $groups = AdInterestGroup::with('interests')->whereIn('id', [1, 2])->get();
    
    $interests = $groups->pluck('interests')->flatten();
    
    $foos = $interests->pluck('foo')->unique();