Php Laravel 5.1:使用相同列名的句柄联接
我正在尝试从数据库中获取以下内容:Php Laravel 5.1:使用相同列名的句柄联接,php,sql,laravel-5.1,Php,Sql,Laravel 5.1,我正在尝试从数据库中获取以下内容: 用户名 用户头像名称 用户化身文件类型 完整的对话信息 使用以下查询: static public function getConversation($id) { $conversation = DB::table('conversation_messages') ->where('belongsTo', $id) ->join('users', 'conversation_messages.se
- 用户名
- 用户头像名称
- 用户化身文件类型
- 完整的对话信息
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
到目前为止,它工作正常,但是化身的列名是“name
”,与“users
”表中的列名类似。
因此,如果我使用此查询通过$conversation->name
获取输出,avatar.name
将覆盖users.name
有没有办法像Laravel5.1中的mysql“as”特性那样重命名查询输出
例如:
$conversation->avatarName
$conversation->userName
嗯,好的。。我找到了一个简单的解决办法
正如您所提到的,我已经在表旁边添加了请求的“As”功能。columnName是的,只需在任一表上重命名该列,它就会工作。
您还可以将user.name列重命名为anything,将对话消息的sender列重命名为id并执行自然连接 看看这个尝试连接三个表的示例:员工、客户和预订(透视表)
我有以下问题,简化的例子:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
$result
是捐赠
模型的集合。但要小心:
两个表都有一个“created_at”列。现在,在执行$result->created_at
时,会显示在处创建的是哪个?我不知道。似乎eloquent在执行连接时执行隐式的select*
,返回模型捐赠
,但带有附加属性<在
处创建的代码>似乎是随机的。所以我真正想要的是,通过电子邮件hello@papabello.com
解决办法是:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
是的,这也是我的第一个想法。但是我认为,一致的命名是每个数据库的一个很好的特性。检查我自己的答案:我找到了一个更好的解决方案在答案中添加代码和示例,以使最终用户更容易阅读和使用。只需输入一堆文本,就很难看到你在说什么。这是一个漂亮的解决方案,非常有用,所以你不会得到一堆不需要的数据。在您发布此内容4年后仍然相关。我们如何使用“selectRaw()”选择相同的内容?
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();