2

I have a Asset model and AssetCategory model. The asset model has function

$this->belongsTo('App\AssetCategory' ); //inverse one to one 

My assets table has columns id , name , assetcategory_id .

Now, when I want to populate my assets list and sort it according to asset name, I can simply write

$assets = Asset::orderBy('name' , 'asc')->get();

But how do I sort according to the asset categories that are populated in my output. I am using laravel 5.3

Bit One
  • 41
  • 4

3 Answers3

0

Join would be simple and will solve your problem.

Asset::select(
'assets.id as asset_id',
'assets.name as asset_name',
'assets.assetcategory_id',
'assetcategories.name as assetcategory_name')
->leftJoin('assetcategories','assetcategories.id','=','assets.assetcategory_id')
->groupBy('asset_id')
->orderBy('assetcategory_name','asc')
->get();

Note: I'm assuming you've used proper naming convention of laravel. Let me know if that works or not.

imrealashu
  • 5,089
  • 4
  • 16
  • 28
  • Thanks for the reply. Sorry your query didnt work. However, I was able to solve the issue using Asset::join('assetcategories', 'assets.assetcategory_id', '=', 'assetcategories.id')->orderby('assetcategories.name','asc')->with('assetcategory')->get(); I also tried eager loading the assetcategories table first. But that produced the same result as before. – Bit One Nov 05 '16 at 13:18
  • well it could have very small glitch because I couldn't try it anywhere. and nice to hear you made it work. :) – imrealashu Nov 05 '16 at 18:36
0

lets assume that you have a function like this in your model

public function assetCategory()
{
  return $this->belongsTo('App\AssetCategory');
}

now in your controller you can fetch asset name

$assets = Asset::orderBy('name' , 'asc')->get();

this way you can fetch asset category

$assets->assetCategory()->orderBy('id', 'asc')->get();

Let me know if this works.

0

You can do it like this...

Asset::join('asset_categories', 'assets.asset_category_id', '=', 'asset_categories.id')
    ->orderBy('asset_categories.name', 'asc')
    ->groupBy('assets.id')
    ->select('assets.*')
    ->get();

Taking assets and asset_categories as table names.

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • Thanks for the reply. Sorry your query didnt work. However, I was able to solve the issue using Asset::join('assetcategories', 'assets.assetcategory_id', '=', 'assetcategories.id')->orderby('assetcategories.name','asc')‌​->with('assetcategor‌​y')->get(); I also tried eager loading the assetcategories table first. But that produced the same result as before. – Bit One Nov 05 '16 at 13:31