拉拉维尔查询工作到一半



我有这个查询

$categories = Category::with('products')
            ->OfListed() // this is my scope has nothing to do with my issues.
            ->orderby('id', 'desc')
            ->take(10)
            ->get();

它工作了一半!意思是:

我通过他们的产品获取我的类别,但我没有按顺序排列它们 id我也得到了它们,而不仅仅是最后 10 个。

我如何在刀片中显示它们:

@foreach($categories as $kis)
  @foreach($kis->products as $ki)
    {{$ki->title}}
  @endforeach
@endforeach

知道吗?

如果你想要 10 个产品并订购,试试这个

$categories = Category::with([
   'products' => function($query){
       $query->orderby('id', 'desc');
    }
 ])->OfListed()->get();

并在刀片中

@foreach($categories as $kis)
  @foreach($kis->products->take(10) as $ki)
    {{$ki->title}}
  @endforeach
@endforeach

编辑的答案,因为 O.P. 说它有效在文档中检查这一点,https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads

如果你尝试

@foreach($categories as $i => $kis)
  <div>Category {{{ $i }}}</div>
  @foreach($kis->products as $ki)
    {{$ki->title}}
  @endforeach
@endforeach

您将看到您只得到 10 个类别。由于您的循环仅显示产品的标题,因此您无法看到获得多少类别。看看您检索产品的方法 - 它可能选择的比预期的更多。

最新更新