Sorting a Laravel Collection by Many to Many Pivot Table Column

时光怂恿深爱的人放手 提交于 2021-02-10 12:45:03

问题


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:

Database:

    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();
    });

Model:

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

View:

<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.

Similar Issues:

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

Laravel eloquent sorting by pivot in many to many relationships


回答1:


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');
}

Or sort the result in Laravel:

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



回答2:


Your error is here pivot_order_column You dont have a column name pivot_order_column you have a column named order_column You can access that on the relationship because you have correctly used withPivot on the relationship.



来源:https://stackoverflow.com/questions/49928725/sorting-a-laravel-collection-by-many-to-many-pivot-table-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!