简体   繁体   English

Laravel:如何按一对一的逆关系排序

[英]Laravel : How to orderBy on a One to One inverse relationship

I have a Asset model and AssetCategory model. 我有一个Asset模型和AssetCategory模型。 The asset model has function asset模型具有功能

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

My assets table has columns id , name , assetcategory_id . 我的assets表具有idnameassetcategory_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 我正在使用laravel 5.3

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. 注意:我假设您使用了laravel的正确命名约定。 Let me know if that works or not. 让我知道是否可行。

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. 让我知道这个是否奏效。

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. assetsasset_categories作为表名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM