代码之家  ›  专栏  ›  技术社区  ›  Dicky Raambo

Laravel5.5雄辩的一对多不工作使用get()

  •  1
  • Dicky Raambo  · 技术社区  · 6 年前

    我有 one to many 关系和需要显示使用where条件。

    findOrFail() 它也起作用了。

    $foo = Model::findOrFail(1);
    

    在我的模板刀片上

    @foreach($foo->bars as $index=>$bar)
    
       {{ $bar->name }}
    
    @endforeach
    

    在我上面的代码中,它正在工作。但是提到 id ,那不是我需要的。

    我需要使用where条件。这样地:

    $foo = Model::where('conditon', 1)->get();
    

    @foreach($foo->条形图作为$index=>$巴)
    
    
    @endforeach公司
    

    然后我得到一个错误:

    此集合实例上不存在ErrorException(E\u ERROR)属性[bars]。

    似乎是在 get() child 具有 $foo->bars

    你是怎么做到的?

    3 回复  |  直到 6 年前
        1
  •  1
  •   N69S    6 年前

    findOrFail()方法返回“Model”的一个实例。

    如果只需要一个结果,请使用first()而不是get()。

    $foo = Model::where('conditon', 1)->first();
    

    @if($foo)
        @foreach($foo->bars as $index=>$bar)
    
           {{ $bar->name }}
    
        @endforeach
    @endif
    

    如果需要多个结果,请执行另一个foreach()。

    @foreach($foo as $oneFoo)
    
        @foreach($oneFoo->bars as $index=>$bar)
    
            {{ $bar->name }}
    
        @endforeach
    
    @endforeach
    

    $foos = Model::where('conditon', 1)->get();
    

    @foreach($foos as $foo)
    
        @foreach($foo->bars as $index=>$bar)
    
            {{ $bar->name }}
    
        @endforeach
    
    @endforeach
    
        2
  •  1
  •   Egretos    6 年前

    尝试使用 ->first() ->get() .

        3
  •  1
  •   thisiskelvin shubham singh    6 年前

    因为 ->get() 检索符合查询条件的多个结果。

    你可以通过 $foo 结果或使用 ->first()