我有一系列的收藏品。在收藏中我有关系。在这些关系中如何使用whereIn
?
$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
}
产品型号中的关系:
public function character()
{
return $this->hasMany('App\Models\ProductCharacter');
}
答案 0 :(得分:1)
尝试一下:
$characters = $category->products()->character()->whereIn('id', [1,2,3,4])->get();
foreach($characters as $character) {
// $character
}
答案 1 :(得分:1)
您似乎需要间接关系。最好的方法是使用hasManyThrough
在您的Category
模型中
public function characters() {
return $this->hasManyThrough(Character::class, Product::class); // Has many characters through products
}
然后您可以直接执行以下操作:
$characters = $category->characters()->whereIn('id', [ 1, 2, 3, 4 ])->get();
答案 2 :(得分:0)
这是什么?我添加了first():
$characters = $category->products()->first()->character()->whereIn('id', [1,2,3,4])->get();
foreach($characters as $character) {
// $character
}
答案 3 :(得分:0)
您可以尝试
$arrayCollections = $category->products()->with('character')->whereIn('id' , [1,2,3,4])->get();
foreach($arrayCollections as $product) {}
答案 4 :(得分:0)
您应该使用whereHas()方法和with()方法。
$arrayCollections = $category->products()
->whereHas('character', function($character){
$character->whereIn('id' , [1,2,3,4]);
})
->with('character')->get();
这将为您提供一系列附加有“字符”且ID为[1,2,3,4]的“产品”。