Laravel - 在多对多 table 关系中按枢轴值排序

Laravel - Order by pivot value in Many to Many table relationship

我的应用程序 (Laravel 5.0) 有一个产品 table 和一个格式 table。这两个 table (format_product) 之间存在多对多关系。一种产品可以以多种形式出售。每个关系都有一个特定的价格,所以我在 format_product table.

中添加了一个 "price" 列

现在我正在尝试按价格对产品进行排序(每个产品的最便宜格式价格作为参考值)。 还有一件事,我需要对结果进行分页。

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() 放入我的模型中,但这应该不是什么大问题。您将不得不使用联接来获得所需的结果。

您可以在控制器中使用以下查询:

public function index() {
    $products = Product::join('format_product', 'format_product.product_id', '=', 'products.id')
                        ->select('products.id', 'format_product.format_id', 'format_product.price')
                        ->orderBy('format_product.price', 'asc')
                        ->paginate(25)
                        ->get();
}

不能按关系对产品进行排序的原因与不能按内部数组对多维数组进行排序的原因相同。

例如:

$array = [
    'key1' => [
        'anotherKey' => 'some value'
    ],
    'key2' => [
        'anotherKey' => 'some other value',
        'anotherKey2' => 'some other value2'
    ],
    'key3' => [
        'anotherKey' => 'yet another value'
    ]
]

您不能按 anotherKey 对这个数组进行排序。您必须使用联接。

希望这对您有所帮助。