【问题标题】:Laravel - Order by pivot value in Many to Many table relationshipLaravel - 在多对多表关系中按枢轴值排序
【发布时间】: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。这样我就不需要每次查询产品的格式时都订购它们。

标签: php mysql laravel pivot


【解决方案1】:

好的,所以我通常不会将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 对该数组进行排序。您必须使用联接。

希望这会有所帮助。

【讨论】:

  • 以防万一有人复制粘贴代码,出现拼写错误,在select语句中应该是'products.id'。
猜你喜欢
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 2020-07-15
  • 1970-01-01
  • 2021-11-25
  • 2019-07-05
相关资源
最近更新 更多