问题
I'm looking at displaying a list of asset
s 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