A
A
Alexander2015-08-17 12:50:20
ORM
Alexander, 2015-08-17 12:50:20

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');
    }

and firms have:
public function contact()
    {
        return $this->hasMany('App\Contact')->withTimestamps();
    }

My task is to display all contacts sorted alphabetically by companies, I don’t understand how to do this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2015-08-17
@Al3xanderG

My task is to display all contacts sorted alphabetically by companies, I don’t understand how to do this.

Incomprehensible task. Need to sort contacts, or companies?
In general, it doesn’t matter what needs to be sorted, for the general case (sorting both contacts and companies):
public function firm()
{
    return $this->belongsTo('App\firm')->orderBy('field', 'asc');
}

public function contacts()
{
    return $this->hasMany('App\App\Contact')->orderBy('field', 'asc');
}

Where field and asc are the sort field and direction respectively.
You can for example like this:
$firms = Firm::orderBy('field', 'asc')->get();
foreach ($firms as $firm) {
    $contact = $firm->contacts()->orderBy('field', 'asc')->get();
}

Or even like this:
$firms = Firm::with('contacts' => function ($q)
{
    return $q->orderBy('field', 'asc');
})->get();

Lots of options. Depends on the task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question