【问题标题】:Passing Array Value in Laravel View在 Laravel 视图中传递数组值
【发布时间】:2018-08-20 15:36:16
【问题描述】:

你能帮我解决这个问题吗.. 我正在尝试显示 foreach 数组中的值.. 关系让我更难理解,所以我选择按我的方式做。

显示类似这样的错误

此集合实例上不存在属性 [pic]。

$dataTagged = DB::table('tagging_tagged')
                ->where('tag_slug', '=',$slug)
                ->get();
foreach($dataTagged as $tagged){
$dataProductquantity[] = Productquantity::where('id','=',$tagged->taggable_id)->first();    
}

我的观点是

@foreach($dataProductquantity as $Productquantity)
            <div class="col-lg-4 col-md-6 mb-4">
              <div class="card h-100">
                <a href="#"><img class="card-img-top" src="{{ asset('productimg') }}/{{$Productquantity->pic}}" alt=""></a>
                <div class="card-body">
                  <h4 class="card-title">
                    <a href="#">{{$Productquantity->product->product_name}}</a>
                  </h4>
                  <h5>&#8369; {{$Productquantity->price}}.00 </h5>
                  <p class="card-text">{{$Productquantity->description}}</p>
                </div>
                <div class="card-footer" align="center">
                <a class="btn btn-warning" align="center"><i class="icon-shopping-cart"></i><span style="color:#fff;">Add to Cart</span></a>
                </div>
              </div>
            </div>
            @endforeach

请帮忙。谢谢

【问题讨论】:

  • 您的错误消息实际上足以告诉您自己解决此问题。但是...不确定如何构建模型,但您可能应该使用$Productquantity-&gt;product-&gt;pic,因为恕我直言,在Productquantity 模型上拥有pic 属性是没有意义的。只需仔细检查pic 的正确位置。不过,您还应该检查为什么视图中的$Productquantity 是一个集合而不是模型本身。

标签: php mysql laravel eloquent relationships


【解决方案1】:

另一种可能是

public function methodName($slug) { 
    // Obtaining the TaggingTagged that include the needed slug. 
    $dataTagged = DB::table('tagging_tagged')->where('tag_slug', '=',$slug)->get();
    // or using the Model to obtain the data
    // $dataTagged = TaggingTagged::where('tag_slug', '=',$slug)->get();

    // Then Iterate into the $dataTagged Collection, the result is a new Collection
    $dataProductquantity = $dataTagged->each(function ($tagged, $key) {
        return Productquantity::where('id','=',$tagged->taggable_id)->first();
    });

    // Passing the $dataProductquantity to the view. You must need replace "viewName"
    return view('viewName')->with(['dataProductquantity' => $dataProductquantity]);
}

【讨论】:

  • 如果能解释一下代码就更好了。仅基于复制和粘贴代码的答案将被删除。
  • 嗨 Jorge,这不是复制粘贴,我认为不需要更详细的解释,即使我添加了 cmets 解释代码。我希望我的答案现在得到了正确解释,并且没有被删除
  • 现在有了 cmets 就更容易理解了。谢谢。
【解决方案2】:

试试这个

$dataProductquantity = [];

foreach($dataTagged as $tagged){
   array_push($dataProductquantity,Productquantity::where('id','=',$tagged->taggable_id)->first());
}

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2019-11-16
    相关资源
    最近更新 更多