【问题标题】:Eager loading when calling a relation调用关系时急切加载
【发布时间】:2017-09-13 12:12:29
【问题描述】:

我的数据库中有这些表,它们是相关的

category
products
product_images
product_categories 

在我拥有的类别模型中(请忽略语法错误)

function ProductCategoryLatest()
{
    return $this->hasMany('App\ProductCategory')->limit(6);
}

在我的 ProductCategory 模型中我有

   function Product(){
       return $this->belongsTo('App\Product')->where('hidden' , 0 );
   }

在我的产品模型中

   function Image(){
       return $this->hasMany('App\Image');
   }

我想在我的索引中显示每个类别的最后 6 个产品 所以我从控制器读取类别并将其发送到我的视图

$categories = Category::all();
return view('index' , compact('category'));

在视图中,我有类似的东西

@foreach($categories as $category)

     {{$category->title }}  products :

     @foreach($category->ProductCategoryLatest as $product_category )

             {{$product_category->Product->title }}

             @foreach($product_category->Product->Image as $image  )
                 <img src="{{$image->title}}">
             @endforeach


     @endforeach

@endforeach

你可以想象有很多查询可以通过预先加载来避免,但问题是限制 6 正在破坏它

如果我像这样写我的查询

$categories = Category::with('ProductCategoryLatest' , 'ProductCategoryLatest.Product' , 'ProductCategoryLatest.Product.Image')->get();

我的数据库中有 5 个类别,查询类似于

select * from product_categories  where category_id  in (1,2,3,4,5) LIMIT 6 

因此,如果 id 为 1 的类别在 product_categories 中有 10 行,则所有 6 个返回的行都属于类别 1,其余的将返回为空,即使它们在 DB 中有关联的行,但限制为 6 会使它们显示在 product_categories 中没有任何行

所以基本上我需要在关系视图中加载类似

@foreach($categories as $category)


    @foreach($category->ProductCategoryLatest->with('Product' , 'Product.Image' ) as $product_category )

    @endforeach


@endforeach

顺便说一句,我知道我可以在控制器中做一些杂耍,比如

$new_categories = [] ;
foreach ($categories as $category )
{
    $ProductCategoryLatest  = ProductCategoryLatest::where('category_id' , $category->id )->with('Product' , 'Product.Image')->get();
    $category->ProductCategoryLatest = $ProductCategoryLatest ;
    $new_categories[] = $category ;
}

但我想知道是否有更清洁的解决方案?


所以总结一下我的关系

class Category extends Model { 
    function ProductCategoryLatest()
    {
        return $this->hasMany('App\ProductCategory')->limit(6);
    }
}

关于这段代码

$categories = Category::with('ProductCategoryLatest')->get();

会生成这个查询

select * from product_categories  where category_id  in (1,2,3,4,5) LIMIT 6 

但我希望每个 category_id 有 6 行而不是像 6 这样的所有行

category_id= 1 -> 6 row 
category_id= 2 -> 6 row
category_id= 3 -> 6 row

....

【问题讨论】:

标签: php laravel laravel-5


【解决方案1】:

好的,您可以从docs 使用take()skip()

$categories = Category::with('ProductCategoryLatest' ,
'ProductCategoryLatest.Product' , 'ProductCategoryLatest.Product.Image')
->skip(0)->take(6)->get();

【讨论】:

  • 抱歉项目暂停了一段时间,这行不通,我编辑了我的问题并在最后添加了一个总结,我认为这让一切都清楚了
  • 您的回答似乎对 Category 选择而不是 ProductCategoryLatest 设置了 6 个限制,不是吗?
  • 是的。它会限制类别我想你需要限制吗?
猜你喜欢
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2014-01-19
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多