Laravel 5.1:使用相同列名的句柄联接 [英] Laravel 5.1: handle joins with same column names

查看:84
本文介绍了Laravel 5.1:使用相同列名的句柄联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to fetch following things from the database:

  • 用户名
  • 用户头像名称
  • 用户avatar_filetype
  • 完成对话消息

带有以下查询:

    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

It works fine so far, but the avatar's column name is 'name' like the column name from the 'users' table. So if I'm using this query the to get the output via $conversation->name, the avatar.name overwrites the users.name

是否有一种方法可以像laravel 5.1上的mysql"as"功能那样重命名查询输出?

Is there a way to rename the query output like the mysql "as" feature at laravel 5.1?

例如:

$conversation->avatarName

$conversation->userName

推荐答案

好吧..我找到了一个简单的解决方法

Meh okay.. i've found a simple solution here

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

您可以提到,我已经在table.columnName旁边添加了请求的按功能"

As you can mention I've added the requested "as-Feature" next to the table.columnName

这篇关于Laravel 5.1:使用相同列名的句柄联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆