【问题标题】:Get next / prev element in Eloquent在 Eloquent 中获取下一个/上一个元素
【发布时间】:2015-08-09 15:17:30
【问题描述】:

我有一个产品和目录模型。它们有多对多的关系,因此我使用了一个名为“项目”的数据透视表。我有一条路线:

/something/something/{catalogue}/{product}

我将产品模型和目录模型传递给视图,该视图输出产品信息和目录信息 - 非常简单。现在我需要 2 个按钮——“下一个”和“上一个”来浏览目录中的产品。

所以一种方法是,我想我会在 Catalog 模型上创建 2 个方法,它们将接受当前产品模型并根据 ID 返回下一个/上一个模型:

public function prevProduct($product){              
    $prevProdId = Product::where('id', '<', $product->id)->max('id');
    return Product::find($prevProdId);
}

public function nextProduct($product){        
    $nextProdId = Product::where('id', '>', $product->id)->min('id');
    return Product::find($nextProdId);
}

现在这工作正常,但正如您所见,它从数据库的 Product 表中检索下一个产品和上一个产品,而不是目录。

要获取目录中的所有产品,可以这样做:$this-&gt;items (on Catalogue model) or $catalogue-&gt;items (from view).

我不知何故需要从目录中获取下一个/上一个项目,但不知道如何。任何建议将不胜感激。

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    你可以像这样过滤Collection:

    $next = $item->id + 1;
    $catalogue->filter(function($item) use ($next ) {
                    return $item->id == $next;
                })->first(); 
    

    我使用添加到 Collection 类的全局方法:

    /**
     * Returns first object from collection which meets attribute criteria
     * 
     * @param string $attributeName   name of attribute we are looking for
     * @param string $attributeValue  value of attribute that have to be met
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findByAttribute($attributeName, $attributeValue)
    {
        return $this->filter(function($item) use ($attributeName, $attributeValue) {
            return $item->{$attributeName} == $attributeValue;
        })->first();        
    }
    

    在这种情况下,我会这样使用这种方法:

    $catalogue->items->findByAttribute('id', $next);
    

    在这两个示例中,我假设您有 $item 对象要引用。

    【讨论】:

      【解决方案2】:

      您可以使用Pagination

      Catalogue::first()->items()->paginate(1);
      

      【讨论】:

        【解决方案3】:

        实际上,它要简单得多。这成功了:

        $nextProdId = $this->items()->where('product_id', '>', $product->id)->min('product_id');        
        return Product::find($nextProdId);
        

        我必须在 'items' 之后添加 () 以启用 'where' 子句并使其基本上可搜索。

        【讨论】:

          猜你喜欢
          • 2010-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-18
          相关资源
          最近更新 更多