Answer the question
In order to leave comments, you need to log in
Joining two tables and sorting in Laravel?
There is a contacts table, it has a foreign key to the firms table, respectively, in the contacts model there is:
public function firm()
{
return $this->belongTo('App\firm');
}
public function contact()
{
return $this->hasMany('App\Contact')->withTimestamps();
}
Answer the question
In order to leave comments, you need to log in
My task is to display all contacts sorted alphabetically by companies, I don’t understand how to do this.
public function firm()
{
return $this->belongsTo('App\firm')->orderBy('field', 'asc');
}
public function contacts()
{
return $this->hasMany('App\App\Contact')->orderBy('field', 'asc');
}
$firms = Firm::orderBy('field', 'asc')->get();
foreach ($firms as $firm) {
$contact = $firm->contacts()->orderBy('field', 'asc')->get();
}
$firms = Firm::with('contacts' => function ($q)
{
return $q->orderBy('field', 'asc');
})->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question