Laravel orderBy on a relationship

It is possible to extend the relation with query functions: <?php public function comments() { return $this->hasMany(‘Comment’)->orderBy(‘column’); } [edit after comment] <?php class User { public function comments() { return $this->hasMany(‘Comment’); } } class Controller { public function index() { $column = Input::get(‘orderBy’, ‘defaultColumn’); $comments = User::find(1)->comments()->orderBy($column)->get(); // use $comments in the template } } … Read more

Laravel – Eloquent “Has”, “With”, “WhereHas” – What do they mean?

With with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of … Read more

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table: student: student_id, first_name, last_name, address_id address: address_id, address, city, zipcode, student_id # you can have a # “link back” if you need You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating … Read more