Laravel 4/5, order by a foreign column

痞子三分冷 提交于 2019-12-25 01:43:32

问题


In Laravel 4/5 how can order a table results based in a field that are connected to this table by a relationship?

My case:

I have the users that only store the e-mail and password fields. But I have an another table called details that store the name, birthday, etc...

How can I get the users table results ordering by the details.name?

P.S.: Since users is a central table that have many others relations and have many items, I can't just make a inverse search like Details::...


回答1:


I would recommend using join. (Models should be named in the singular form; User; Detail)

$users = User::join('details', 'users.id', '=', 'details.user_id')  //'details' and 'users' is the table name; not the model name
    ->orderBy('details.name', 'asc')
    ->get();

If you use this query many times, you could save it in a scope in the Model.

class User extends \Eloquent {
    public function scopeUserDetails($query) {
        return $query->join('details', 'users.id', '=', 'details.user_id')
    }
}

Then call the query from your controller.

$users = User::userDetails()->orderBy('details.name', 'asc')->get();


来源:https://stackoverflow.com/questions/27090935/laravel-4-5-order-by-a-foreign-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!