ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php-Lravel 5.4:获取具有收藏夹的产品并为每个用户显示收藏夹产品

2019-11-09 05:30:30  阅读:245  来源: 互联网

标签:laravel-5-4 laravel eloquent php


我正在尝试获取所有具有收藏夹的产品,并将其显示为好像用户已登录,并且此收藏夹中的产品将显示为收藏夹,否则他可以将其添加到收藏夹.

这是我的控制器

$products = ( new Product )
            ->where( 'quantity', '>', 0 )
            ->with( 'favorite' )
            ->orderBy( 'price', $sort )->get();

现在,如果我使dd($product-> favorite),我将得到喜欢的数组

[{"id":1,"product_id":7,"user_id":1,"created_at":"2018-04-01 09:16:23","updated_at":"2018-04-01 09:16:23"}]

但是如果我尝试选择此数组中的任何一个,例如{{$product-> favorite-> product_id}}

我懂了

Property [product_id] does not exist on this collection instance

我如何在刀片中显示

    @foreach($products as $product)
            <div class="col-md-4 col-sm-6">
                 <div class="thumbnail no-border no-padding">
                      <div class="media">
                      <a class="media-link" href="{!! URL::route('products.show', $product->id) !!}">
                      {!! Html::image('images/products/'.$product->image, $product->name) !!}
                      <span class="icon-view">
                      <strong><i class="fa fa-eye"></i></strong>
                      </span>
                      </a>
                     </div>
                     <div class="caption text-center">
                          <h4 class="caption-title">{!! $product->name !!}</h4>

                         <div class="price">
                         <ins>{!! $product->price !!}</ins>
                         {{--<del>$425.00</del>--}}
                         </div>
                         {{ $product->favorite->product_id }}
                      <div class="buttons">
                     @if(count($product->favorite) == 1)
                      <span class="btn btn-theme btn-theme-transparent">
                      <i class="fa fa-heart text-danger"></i>
                     </span>
                     @else
                     {!! Form::open(['route'=>'favorite.store', 'class'=>'favorite-products']) !!}
                     {!! Form::hidden('product_id', $product->id) !!}
                     @if ( Auth::guard( 'web' )->check() != 0 )
                     {!! Form::hidden('user_id', Auth::guard( 'web' )->user()->id) !!}
                     @endif
                     <button class="btn btn-theme btn-theme-transparent btn-wish-list">
                     <i class="fa fa-heart"></i>
                     </button>
                     @endif


                    {!! Form::close() !!}


                  {!! Form::open(['route'=>'add.to.cart', 'class'=>'btn product-shoppingcart-icon']) !!}
                 {!! Form::hidden('pro_id', $product->id) !!}
                 <button class="btn btn-theme btn-theme-transparent btn-icon-left">
                 <i class="fa fa-shopping-cart"></i>{{ trans('interface.addToCart') }}
                 </button>
                {!! Form::close() !!}
                <a class="btn btn-theme btn-theme-transparent btn-compare"
                href="#"><i class="fa fa-exchange"></i></a>
                </div>
              </div>
        </div>
    </div>
@endforeach

解决方法:

我认为当前查询效率低下.据我了解,产品可以被许多用户喜欢.如果然后为每个产品加载所有收藏夹,则还将加载与当前用户无关的收藏夹.因此,您应该只选择相关的收藏夹:

$products = Product::query()
    ->where('quantity', '>', 0)
    ->with(['favorite' => function ($hasMany) {
        $hasMany->where('user_id', \Auth::user()->id);
    }])
    ->orderBy('price', $sort)
    ->get();

然后,您将最终获得每种产品的收藏夹集合,尽管在该收藏夹中最多只能包含一个收藏夹(因为当前用户只喜欢一次产品,对吗?).因此,您想通过以下方式访问视图中的内容:

@foreach($products as $product)
    // ... your html here
    @if(count($product->favorite))
        <span class="btn btn-theme btn-theme-transparent">
            <i class="fa fa-heart text-danger"></i>
        </span>
    @endif
    // ... more html
@endforeach

说明:$product-> favorite是一个集合,因此count()将为您提供项目数.由于当前用户可能没有任何收藏夹或只有一个收藏夹,因此我们收到的结果为0或1,也可以分别视为false和true.

编辑:为了避免未登录用户的问题,您可以使用此查询,此查询只会简单地不加载收藏夹关系.

$products = Product::query()
    ->where('quantity', '>', 0)
    ->orderBy('price', $sort)
    ->when(\Auth::check(), function ($query) {
        $query->with(['favorite' => function ($hasMany) {
            $hasMany->where('user_id', \Auth::user()->id);
        }]);
    })
    ->when(\Auth::guest(), function ($query) {
        $query->with(['favorite' => function ($hasMany) {
            // will exclude all rows but flag the relation as loaded
            // and therefore add an empty collection as relation
            $hasMany->whereRaw('1 = 0');
        }]);
    })
    ->get();

或者,如果有人不喜欢总是返回零行的怪异数据库调用,我们也可以手动设置该关系:

$products = Product::query()
    ->where('quantity', '>', 0)
    ->orderBy('price', $sort)
    ->when(\Auth::check(), function ($query) {
        $query->with(['favorite' => function ($hasMany) {
            $hasMany->where('user_id', \Auth::id());
        }]);
    })
    ->get();

if (\Auth::guest()) {
    $products->each(function ($product) {
        $product->setRelation('favorite', new \Illuminate\Database\Eloquent\Collection());
    });
}

标签:laravel-5-4,laravel,eloquent,php
来源: https://codeday.me/bug/20191109/2011936.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有