首页 > 解决方案 > Mysql join 选择多列最佳实践

问题描述

我正在使用Laravel Query Builder ,并且我的 join 语句运行良好。

User表列:

name|email|phone|gender

School_Abouts表列:

courses|boards|contact|location|teachers

目前我做如下选择查询:

$school=User::join('school_abouts', 'users.id', '=', 'school_abouts.school_id')
                ->where('users.id',$id)
                ->select('users.name',
                        'users.email',
                        'users.phone',
                        'school_abouts.courses',
                        'school_abouts.boards',
                        'school_abouts.contact',
                        'school_abouts.location',
                        'school_abouts.teachers')
                ->first();

要从school_about表中选择列,我必须多次写入表名。但是有没有办法传递一个列数组呢?我试过这个但失败了:

->select('users.name',
   'users.email',
   'users.phone',
   'school_abouts'.[courses,boards,location,contact,teachers],
)

标签: mysqljoinlaravel-query-builder

解决方案


您可以安全地从列中删除表名,因为两个表中没有共同的列名,但正如我所见,您正在尝试从两个表中获取几乎所有列,这可以使用以下方法进行简化*

$school = User::join('school_abouts', 'users.id', '=', 'school_abouts.school_id')
                ->where('users.id', $id)
                ->select('users.*', 'school_abouts.*')
                ->first();

但是,如果您想获取某些列并且它们的名称可能会产生歧义,那么必须在列名前加上表名。为了使其更短,您可以使用别名:

$school = User::join('school_abouts AS sa', 'users.id', '=', 'sa.school_id')
                ->where('users.id', $id)
                ->select('users.name',
                        'sa.courses',
                        'sa.boards',
                        'sa.contact',
                        'sa.location')
                ->first(); 

推荐阅读