-1

i have a project where i can access to company name like this:

$user->atc_results->first()->atc_company->name; 

i'm tryng to order my results orderBy company_name but it doesn't work.

public function atc_results()
{
   return $this->hasMany('Modules\Atc\Entities\AtcResult')->with("atc_company")->orderBy("atc_company.name","asc");
}

can you help me ?

Diego Cespedes
  • 1,353
  • 4
  • 26
  • 47

2 Answers2

1

Try to use the closure within the array when calling with() to add further query elements to your atc_company relation:

public function atc_results()
{
   return $this->hasMany('Modules\Atc\Entities\AtcResult')
            ->with(['atc_company' => function($q) {
                $q->orderBy('name', 'desc');
            }]);
}
Mouad ZIANI
  • 132
  • 1
  • 8
0

Probably going the other way around will work

class AtcCompany extends Model
{
    public function atcResults()
    {
        //Asumption that relation is belongsTo
        //Check the foreign key and owner key as per db
        return $this->belongsTo(AtcResult::class);
    }
}

//Somewhere in some controller method
function atc_companies()
{
    //$results will still contain data for both AtcResult & AtcCompany
    $results = AtcCompany::with('atcResults')->orderBy('name', 'asc')->get();
    
   
    return $results;
}
Donkarnash
  • 12,433
  • 5
  • 26
  • 37