【问题标题】:Get the items in same category in Laravel Many to Many Eloquent relationship在 Laravel 多对多 Eloquent 关系中获取同一类别的项目
【发布时间】:2016-06-06 17:43:38
【问题描述】:

有一个类别和产品。

类别可以是“推荐”、“鞋子”、“衬衫”等,产品可以是“耐克衬衫”、“阿迪达斯鞋”等。

Category
id
name

Product
id
name

CateogryProducts 
cat_id
product_id

我想从产品列表中获取下一个和上一个产品 ID,但是,该列表需要属于特定类别。

例如,如果我提供鞋子类别,则获取鞋子列表,并根据产品 id 获取下一个鞋子和上一个鞋子的产品 id。

$this->data['category'] = Category::find($cat);
$product = Product::find($id);
$this->data['prev'] = Product::where('id', '<', $product->id)->max('id');
$this->data['next'] = Product::where('id', '>', $product->id)->min('id');

这是我获取下一个/上一个 ID 的尝试,有没有办法将列表限制为同一类别?

非常感谢

【问题讨论】:

标签: php mysql sql laravel eloquent


【解决方案1】:

如果你已经正确建立了关系,你会很好的:

$prev = Product::with(['categories' => function($query){
      $query->where('id', $cat_id);
    }])->where('id', '<', $id)->orderBy('id', 'desc')->first();

$next = Product::with(['categories' => function($query){
      $query->where('cat_id', $cat_id);
    }])->where('id', '>', $id)->orderBy('id', 'asc')->first();

它没有经过测试,可能需要一些调整并以你需要的正确方式调整 asc/desc,但这是要走的路

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 2016-07-20
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2017-04-20
    • 2019-06-13
    • 2020-12-16
    • 2021-04-21
    相关资源
    最近更新 更多