douping4436
2018-09-24 07:19
浏览 747
已采纳

Laravel whereIn in array

I have array of collections. In collections I have relation. How I can use whereIn in these relations?

$arrayCollections = $category->products;

$arrayCollections = $arrayCollections->character->whereIn('id', [1,2,3,4]); //I need use whereIn in character relation. I get error: Property [character] does not exist on this collection instance.

foreach($arrayCollections as $product) {
    .... //but in foreach I can use $product->character
}

Relation in product model::

public function character()
{
    return $this->hasMany('App\Models\ProductCharacter');
}

图片转代码服务由CSDN问答提供 功能建议

我有一系列集合。 在收藏中我有关系。 我如何在这些关系中使用 whereIn

  $ arrayCollections = $ category-> products; 
 
 $ arrayCollections = $ arrayCollections-  > character-> whereIn('id',[1,2,3,4]);  //我需要在字符关系中使用whereIn。 我收到错误:此集合实例上不存在属性[character]。
 
foreach($ arrayCollections as $ product){
 .... //但在foreach中我可以使用$ product-> character 
  } 
   
 
 

产品型号中的关系::

 公共函数字符()
 {
返回$  this-> hasMany('App \ Models \ ProductCharacter'); 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dongshenjie3055 2018-09-24 07:33
    已采纳

    Try this:

    $characters = $category->products()->character()->whereIn('id', [1,2,3,4])->get();
    
    foreach($characters as $character) {
        // $character
    }
    
    已采纳该答案
    打赏 评论
  • dstd2129 2018-09-24 07:48

    You seem to need an indirect relationship. The best way to get this is by using hasManyThrough

    In your Category model

    public function characters() {
         return $this->hasManyThrough(Character::class, Product::class); // Has many characters through products
    }
    

    Then you can directly do:

     $characters = $category->characters()->whereIn('id', [ 1, 2, 3, 4 ])->get();
    
    打赏 评论
  • duannan4486 2018-09-24 08:02

    what about this ? I added first() :

    $characters = $category->products()->first()->character()->whereIn('id', [1,2,3,4])->get();
    
    foreach($characters as $character) {
        // $character
    }
    
    打赏 评论
  • douchuang8359 2018-09-24 08:41

    You can try this

    $arrayCollections = $category->products()->with('character')->whereIn('id' ,  [1,2,3,4])->get();
    
    foreach($arrayCollections as $product) {}
    
    打赏 评论
  • douji2283 2018-09-24 09:45

    You should use the whereHas() methode and with() method.

    $arrayCollections = $category->products()
        ->whereHas('character', function($character){
            $character->whereIn('id' ,  [1,2,3,4]);
        })
        ->with('character')->get();
    

    This will get you a collection of "products" that have "characters" attach to it that have ID in [1,2,3,4].

    打赏 评论

相关推荐 更多相似问题