仅通过多对多产品类别关系中的预先加载获取 X 产品模型


fetch only X Product Model via eager loading in a ManyToMany Product Category relationship

我在类别和产品模型之间有一个多对多的关系。

产品型号是这样的:

class Product extends Model
    {
        protected $primaryKey = 'product_id';
        public function categories ()
        {
            return $this->belongsToMany('App'Category', 'category_product', 'product_id', 'cat_id');
        }
}

类别模型为:

class Category extends Model
        {
            protected $primaryKey = 'cat_id';
            public function products (){
            return $this->belongsToMany('App'Product','category_product','cat_id','product_id');
        }
    }

现在,我只想获取每个类别的最后 4 个(例如)产品。 为此,我写了这个:

$categories =   Category::with([
    'products'  =>  function($query){
        $query->select('products.product_id')->orderBy('created_at','desc')->take(4);
    }
])->get();

但这不能正常工作,退回意外的产品算数?

我该怎么做?

如果您想要每个类别的最后 X 个产品数量,您可以尝试如下:

Category::with(['products' => function($query) {
    $query->orderBy('updated_at','desc')->take(X);
}])->get();

这应该返回一个类别集合,其中每个类别的产品数量不应超过所需的产品数。

希望对您有所帮助。