欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

联合查询 相同的列名 laravel join same column name

selectRaw('packages.name as name1, assigned_packages.name as name2') 与 select(DB::raw('packages.name as name1, assigned_packages.name as name2'))是一样的


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

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


I do currently use this code to retrieve the required data from my database

    $query = DB::table('packages')
        ->join('assigned_packages', function($join) use($id)
        {
            $join->on('packages.id', '=', 'assigned_packages.registered_package_id')
                ->where('assigned_packages.customer_id', '=', $id);
        })
        ->join('registered_packages', function($join)
        {
            $join->on('packages.id', '=', 'registered_packages.id')
                ->on('registered_packages.id', '=', 'assigned_packages.registered_package_id');
        });
它工作正常,但问题是这个表具有相同名称的列,因此只有最后一个在结果中。我该如何解决?通常我会as在查询中使用该选项,但我真的不知道如何从上面将其添加到我当前的JOIN代码中。
正确答案
$query = DB::table('packages')
->join(...)
->join(...)
->select(DB::raw('packages.name as name1, assigned_packages.name as name2'))
->get();

$sql = "select a.name as name1, b.name as name2"; $sql .= " from a left join b on a.id=b.id1 and b.id2=&id"; $result = DB::select($sql);
来自 http://stackoverflow.com/questions/25859626/laravel-4-join-same-column-name



DB::table('cases') ->join('contacts', 'cases.id', '=', 'contacts.id') ->select('cases.name', 'contacts.name') ->get();
正确答案

DB::table('cases') ->join('contacts', 'cases.id', '=', 'contacts.id') ->selectRaw('cases.name as cases_name, contacts.name as contacts_name') ->get();

来自 http://stackoverflow.com/questions/24791984/laravel-query-with-joins-same-name-in-multiple-tables
普通分类: