【问题标题】:Laravel - hasManyThrough with Limit/TakeLaravel - hasManyThrough with Limit/Take
【发布时间】:2015-09-10 05:10:21
【问题描述】:

我有产品、子类别、类别关系..

在我定义 hasManyThrough 关系的类别模型中:

public function products()
{
    return $this->hasManyThrough('Products','SubCategory');
}

如何在每个类别中仅显示 4 个产品?

$products = Category::with('products')->get()

我已经在 hasManyThrough 关系上添加了 take(2) 或 limit(2),但是查询限制了整体产品,而不是子类别。这是查询日志:

select products.*, subcategories.category_id from products inner join subcategories on subcategories.id = products.subcategory_id where subcategories.category_id in (?, ?, ?, ?, ?, ?) limit 4

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    我不认为你可以设置 hasManyTrough 关系限制,但你可以分离你的关系并为它们设置自己的限制:

    类别有子类别:

    public function subcategories()  
    {
        return $this->hasMany('Subcategory')->limit(2);
    }
    

    子类别有产品:

    public function products()  
    {
        return $this->hasMany('Product')->limit(4);
    }
    

    然后你可以调用:

    Category::with('subcategories.products')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2014-08-14
      相关资源
      最近更新 更多