通过多对多数据透视表列对Laravel集合进行排序 [英] Sorting a Laravel Collection by Many to Many Pivot Table Column

查看:67
本文介绍了通过多对多数据透视表列对Laravel集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看在数据透视表上以 order_column 定义的顺序显示属于 product 资产的列表 product_asset .在这种情况下, sortBy 函数没有影响.不会引发任何错误,但是无论如何它都会以相同的顺序返回集合数组.

I'm looking at displaying a list of assets belonging to a product in an order defined by order_column on the pivot table product_asset. In this case, the sortBy function has no effect. No errors are thrown, but it returns the collection array in the same order no matter what.

这是我目前布置的内容:

Here's what I have laid out currently:

数据库:

    Schema::create('product_asset', function (Blueprint $table) {
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

        $table->integer('asset_id')->unsigned()->index();
        $table->foreign('asset_id')->references('id')->on('assets')->onDelete('cascade');

        $table->unsignedInteger('order_column')->nullable();
    });

型号:

/**
 * The assets that belong to the product.
 */
public function assets()
{
    return $this->belongsToMany('App\Asset', 'product_asset')->withPivot('order_column');
}

查看:

<ul>
    @foreach($resources->sortBy('pivot_order_column') as $resource)
        <li><a href="{{ $resource->url }}">{{ $resource->name }}</a></li>
    @endforeach
</ul>

在此方面的任何帮助,我将不胜感激!预先感谢.

I would be very appreciative of any help on this one! Thanks in advance.

类似问题:

https://laravel.io/forum/04-17-2014-order-by-pivot-table-at-attribute-in口才

Laravel雄辩式排序关系

推荐答案

您可以使用Indra的建议对查询进行排序:

You can order the query using Indra's suggestion:

public function assets()
{
    return $this->belongsToMany('App\Asset', 'product_asset')->withPivot('order_column')
        ->orderBy('product_asset.order_column');
}

或在Laravel中对结果进行排序:

Or sort the result in Laravel:

$resources->sortBy('pivot.order_column')

这篇关于通过多对多数据透视表列对Laravel集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆