mardi 20 septembre 2016

Laravel 5.0 how to order an eloquent with() query

I have two models: item and faq. The are in a belongsToMany with each other with a correctly created join table: item_faq (singular of both). My join table has an additional field on it for order.

In my view I get all the faq's and if they have a pivot table record I output "checked" on a checkbox. I also have drag and drop ordering on the checkbox list and that works well.

A few code notes:

// ITEMS MODEL
public function faqs(){
        return $this->belongsToMany('App\Faq');
    }

// FAQ MODEL
public function deals(){
    return $this->belongsToMany('App\Deal');
}

public function hasDeal($deal) {
    $deals = $this->deals->lists('id');
    return in_array($deal, $deals);
}

Schema of join table:

  • item_id
  • faq_id
  • order
  • timestamps

My issue is that they faq's don't load sorted by the order column on the pivot table.

I am using a very simple:

$faqs = \App\Faq::with('items')->get();

To retrieve the FAQ's and this works at getting all the faq's and if they are related, it checks the checkbox.

How can I order these by the order column on the join table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire