Mysql join selects multiple column最佳实践

Mysql join selects multiple column best practice

我正在使用 Laravel 查询生成器 并且我的连接语句运行良好。

User table 列:

name|email|phone|gender

School_Abouts table 列:

courses|boards|contact|location|teachers

目前我select查询如下:

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

到select来自school_abouttable的列我必须多次写table名字。但是有没有办法传递一个列数组呢?我试过了但失败了:

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

您可以安全地从列中删除 table 名称,因为在两个 table 中没有共同的列名称,但正如我所见,您正试图从 table 中获取几乎所有列 tables 可以使用 *:

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

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

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