本文介绍了Laravel 4/5,由外国专栏命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的情况:

在Laravel 4/5中,如何在一个与该表相关联的字段中排列表格结果?

我有用户,只存储电子邮件密码字段。但是我有另一个表的细节存储名称生日等...



如何获取用户表结果按 details.name



PS:由于用户是一个具有许多其他关系并有很多项目的中心表, t只做一个反向搜索,如 Details :: ...

解决方案

我建议使用join。 (模型应以单数形式命名;用户;细节)

  $ users = User :: join('details' 'users.id','=','details.user_id')//'details'和'users'是表名;不是模型名称
- > orderBy('details.name','asc')
- > get();

如果您多次使用此查询,可以将其保存在Model中的范围内。 p>

 类用户扩展\Eloquent {
public function scopeUserDetails($ query){
return $ query-> ; join('details','users.id','=','details.user_id')
}
}

然后从控制器调用查询。

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


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::...

解决方案

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();

这篇关于Laravel 4/5,由外国专栏命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:31