duanleiming2014 2018-05-06 23:26
浏览 40
已采纳

循环数据库结果似乎只执行一次

I am handling an ajax request and querying my database in my controller.

Controller:

    $prod_id = $request->prod_type;

    $data = types::where('id', $prod_id)->with('products')->get(); 

    return view('pages.types')->with('data',$data);

When $data is returned it shows all products based on the queried type from the database. However when looping through $data in my view it seems to loop only once and displays only one card.

View:

            @foreach($data as $type )
        <div class="col-sm-3 mb-3">
            <div class="card h-100">
                <div class="card-body">
                    <h4 class="card-title"><a href="/products/{{$type->products[0]->id}}">{{$type->products[0]->Product_Name}}</a></h4>
                    <p class="card-text">...</p>                        
                 </div>
            </div>
        </div>
        @endforeach

I realise I am only asking for the first object with products[0] but if omitted I get property[id] does not exists in collection instance error.

  • 写回答

1条回答 默认 最新

  • dongtieshang5429 2018-05-06 23:35
    关注

    I think you're looping over the type here, but you actually want to be looping over the products. Try this:

    @foreach($data[0]->products as $product )
    <div class="col-sm-3 mb-3">
        <div class="card h-100">
            <div class="card-body">
                <h4 class="card-title"><a href="/products/{{$product->id}}">{{$product->Product_Name}}</a></h4>
                <p class="card-text">...</p>                        
             </div>
        </div>
    </div>
    @endforeach
    

    UPDATE:

    Okay, I've updated the code sample so that it will just loop over the first Type object's products - I assume that's what you want as it looks like the Controller is only getting one type anyway?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog