Laravel 5.1:如何处理具有相同列名的联接

35

我正在尝试从数据库中获取以下内容:

  • 用户名称
  • 用户头像名称
  • 用户头像文件类型
  • 完整的对话消息

使用以下查询语句:

    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

有没有办法像MySQL的“as”特性那样在Laravel 5.1中重命名查询输出?

例如:

$conversation->avatarName

$conversation->userName
4个回答

73

哦,还好..我找到了一个简单的解决方案这里

->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')

正如您所提到的,我已经在表格列名旁边添加了所请求的"as-Feature"。


3
漂亮的解决方案并且非常有用,这样你就不会得到你不需要的一堆数据。即使是在你发布这篇文章4年之后,它仍然是相关的。 - logos_164
我们如何使用 'selectRaw()' 来选择相同的内容? - Michel
简单明了。 - Godwin

14

看一下这个尝试连接三个表staffs、customers和bookings(数据透视表)的例子。

 $bookings = \DB::table('bookings')
        ->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
        ->join('customers', 'customers.id' , '=', 'bookings.customer_id')
        ->select('bookings.id', 'bookings.start_time',  'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name',  'customers.name as Customer-Name')
        ->orderBy('customers.name', 'desc')
        ->get();
    return view('booking.index')
            ->with('bookings', $bookings);

10

我遇到了以下问题,这是一个简化的例子:

$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();

$result 是一组 Donation 模型。但要小心:

两个表格都有一个 'created_at' 列。现在,当执行 $result->created_at 时,显示哪个 created_at?我不知道。看起来 Eloquent 在执行联接时会隐式地选择 select *,返回模型 Donation 但带有额外的属性。 created_at 看起来是随机的。因此,我真正想要的是返回所有邮箱为 hello@papabello.com 的用户的 Donation 模型。

解决方案如下:

$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();

-4

是的,只需在任一表上重命名列即可。 您还可以将user.name列重命名为任何内容,将conversation_messages的sender列重命名为id并执行自然连接。


是的,那也是我的第一想法。但我认为,在每个数据库中保持一致的命名是一个很好的特性。 请检查我的回答:我找到了一个更好的解决方案。 :) - Florian Lauterbach
在你的回答中添加代码和示例,使其更易于阅读和使用。仅键入一堆文本会使你所说的内容难以理解。 - logos_164

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接