【发布时间】:2015-07-27 08:16:19
【问题描述】:
我的应用程序 (Laravel 5.0) 有一个 Products 表和一个 Formats 表。这两个表 (format_product) 之间存在多对多关系。一种产品可以以多种形式出售。每个关系都有一个特定的价格,所以我在 format_product 表中添加了一个“价格”列。
现在我正在尝试按价格对产品进行排序(作为每个产品的最便宜格式价格作为参考值)。 还有一件事,我需要对结果进行分页。
class Product extends Model {
public function formats()
{
return $this->belongsToMany('App\Format')->withPivot('price')->orderBy('pivot_price', 'asc');
}
}
class Format extends Model {
public function products()
{
return $this->belongsToMany('App\Product')->withPivot('price');
}
}
这是 format_product_pivot:
Schema::create('format_product', function(Blueprint $table) {
$table->integer('format_id')->unsigned()->index();
$table->foreign('format_id')->references('id')->on('formats')->onDelete('cascade');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->decimal('price', 8, 2);
});
例如,具有以下值:
Product A - Format 1 = 15€
Product A - Format 2 = 10€
Product B - Format 1 = 8€
Product B - Format 2 = 20€
Product C - Format 3 = 5€
Product C - Format 1 = 2€
我想要这个结果:
Product C - 1 ( 2€)
Product B - 1 ( 8€)
Product A - 2 (10€)
【问题讨论】:
-
是的,这就是我需要的。我知道按关系值排序的限制。正如你所说,这与多维数组的问题相同......我想我试图找到最优雅的方式来解决这个问题。关于在模型关系中添加 orderBy。这样我就不需要每次查询产品的格式时都订购它们。