【问题标题】:Laravel whereIn in arrayLaravel whereIn 在数组中
【发布时间】:2018-09-24 17:45:21
【问题描述】:

我有一系列收藏。在收藏中我有关系。我如何在这些关系中使用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');
}

【问题讨论】:

  • $arrayCollections 中有什么内容?
  • 显示你的数据库表和定义字符的位置
  • character - 模型产品关系
  • 您是否尝试过dd($arrayCollections) 来查看character 是否在集合中?
  • @kerbholz 不,在arrayCollections 我得到数组。是的,我的收藏中有character

标签: php laravel


【解决方案1】:

试试这个:

$characters = $category->products()->character()->whereIn('id', [1,2,3,4])->get();

foreach($characters as $character) {
    // $character
}

【讨论】:

  • Method Illuminate\Database\Query\Builder::character does not exist.
【解决方案2】:

您似乎需要间接关系。最好的方法是使用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();

【讨论】:

  • Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous
【解决方案3】:

这个呢?我添加了 first() :

$characters = $category->products()->first()->character()->whereIn('id', [1,2,3,4])->get();

foreach($characters as $character) {
    // $character
}

【讨论】:

    【解决方案4】:

    你可以试试这个

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

    【讨论】:

      【解决方案5】:

      你应该使用 whereHas() 方法和 with() 方法。

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

      这将为您提供一个“产品”集合,这些“产品”附加了“字符”,其 ID 在 [1,2,3,4] 中。

      【讨论】:

        猜你喜欢
        • 2017-05-30
        • 2015-08-22
        • 2014-05-10
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        • 2017-05-19
        • 2021-03-23
        • 1970-01-01
        相关资源
        最近更新 更多