Laravel order according to the corresponding table

My project has models of products and categories. This product belongs to the category. Since the product has a foreign key category_id, I could easily sort the output as follows:

$products = Product::orderBy('category_id', 'asc')->get(); 

But what I really wanted was to sort by category name by category, so I tried:

 $products = Product::with(['categories' => function($q){ $q->orderBy('name', 'asc')->first(); }]); 

But it doesn’t output anything. As a test, I returned return Product::with('categories')->first(); and he displays a penalty ...

Here is the "Sensitivity" relationship.

product

 class Product extends Model { protected $fillable = [ 'name', 'description', 'price', 'category_id', ]; protected $hidden = [ 'created_at', 'updated_at', ]; public function categories() { return $this->belongsTo('\App\Category', 'category_id'); } } 

Category:

 class Category extends Model { protected $fillable = [ 'name' ]; public function products() { return $this->hasMany('\App\Product'); } } 

And part of the view:

 @foreach ($products as $product) <tr> <td>{!! $product->categories->name !!}</td> <td> @if(!empty($product->picture)) Yes @else No @endif </td> <td>{!! $product->name !!}</td> <td>{!! $product->description !!}</td> <td>{!! $product->price !!}</td> <td> <a href="{{ url('/product/'.$product->id.'/edit') }}"> <i class="fa fa-fw fa-pencil text-warning"></i> </a> <a href="" data-href="{{route('product.destroyMe', $product->id)}}" data-toggle="modal" data-target="#confirm-delete"> <i class="fa fa-fw fa-times text-danger"></i> </a> </td> </tr> @endforeach 
+5
source share
3 answers

I have not tested this, but I think it should work

 // Get all the products $products = \App\Product::all(); // Add Closure function to the sortBy method, to sort by the name of the category $products->sortBy(function($product) { return $product->categories()->name; }); 

This should also work:

  $products = Product::with('categories')->get() ->sortBy(function($product) { return $product->categories->name; }) 
+3
source

You can use join (), try under the code

 $query = new Product; //new object //$query = Product::where('id','!=',0); $query = $query->join('categories', 'categories.id','=','products.categories.id'); $query = $query->select('categories.name as cat_name','products.*'); $query = $query->orderBy('cat_name','asc'); $record = $query->get(); 
+3
source

In laravel, you cannot order through a linked table without manually joining the linked table, which is really very inconvenient, but this package can do this for you out of the box https://github.com/fico7489/laravel-eloquent-join

0
source

Source: https://habr.com/ru/post/1247913/


All Articles