doudi5892 2016-01-28 09:42
浏览 80

在ManyToMany产品类别关系中通过急切加载仅获取X产品模型

I have a ManyToMany relationship between Category and Product Model.

Product Model is like this :

class Product extends Model
    {
        protected $primaryKey = 'product_id';

        public function categories ()
        {
            return $this->belongsToMany('App\Category', 'category_product', 'product_id', 'cat_id');
        }
}

And Category Model is :

class Category extends Model
        {
            protected $primaryKey = 'cat_id';

            public function products (){
            return $this->belongsToMany('App\Product','category_product','cat_id','product_id');
        }
    }

Now , I want to fetch only last 4(for example) products of each Category. for that I write this :

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

But this does not work properly and return unexpected products count?

How Can I do that?

  • 写回答

1条回答 默认 最新

  • doujing2017 2016-01-28 15:42
    关注

    If you want the last X number of products per category you can try something like :

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

    This should return a Collection of Categories in which you should have no more than the desired number of products per category.

    Hope it helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败