Php 以雄辩的方式获取下一个/上一个元素
我有一个产品和目录的模型。它们具有多对多关系,因此我使用一个名为“items”的透视表。我有一条路线:Php 以雄辩的方式获取下一个/上一个元素,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有一个产品和目录的模型。它们具有多对多关系,因此我使用一个名为“items”的透视表。我有一条路线: /something/something/{catalogue}/{product} 我将产品模型和目录模型传递给视图,视图直接输出产品信息和目录信息。现在我需要有两个按钮——“下一个”和“上一个”来浏览目录中的产品 这样做的一种方法是,我想我会在目录模型上创建两种方法,它们会接受当前产品模型并基于ID返回下一个/上一个模型: public function prevProduct($pro
/something/something/{catalogue}/{product}
我将产品模型和目录模型传递给视图,视图直接输出产品信息和目录信息。现在我需要有两个按钮——“下一个”和“上一个”来浏览目录中的产品
这样做的一种方法是,我想我会在目录模型上创建两种方法,它们会接受当前产品模型并基于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){
$prevProdId=Product::where('id','',$Product->id)->min('id');
返回产品::find($nextProdId);
}
现在这很好,但正如您所看到的,它从数据库中的产品表中检索下一个产品和上一个产品,而不是从目录中检索
要获取目录中的所有产品,可以这样做:$this->items(在目录模型上)或$catalog->items(从视图中)。
我不知何故需要从目录中获取下一个/上一个项目,但不知道如何获取。如果您有任何建议,我们将不胜感激。您可以筛选收藏,如下所示:
$next = $item->id + 1;
$catalogue->filter(function($item) use ($next ) {
return $item->id == $next;
})->first();
我使用添加到集合类的全局方法:
/**
* 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
对象。您可以使用
实际上,这要简单得多。这就成功了:
$nextProdId = $this->items()->where('product_id', '>', $product->id)->min('product_id');
return Product::find($nextProdId);
我必须在“items”之后添加()以启用“where”子句并使其基本上可搜索
$nextProdId = $this->items()->where('product_id', '>', $product->id)->min('product_id');
return Product::find($nextProdId);