TheNiceGuy
TheNiceGuy

Reputation: 3730

Laravel 4 - JOIN - Same column name

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');
        });

It works fine, however the problem is that this tables have columns with the same name, and therefore only the last one is in the result. How can i fix that? Normally i would use the as option in the query, but i honestly do not know how I can add it to my current JOIN code from above.

Upvotes: 2

Views: 4541

Answers (1)

worldask
worldask

Reputation: 1837

$query = DB::table('packages')
->join(...)
->join(...)
->select(DB::raw('packages.name as name1, assigned_packages.name as name2'))
->get();

edit:

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

Upvotes: 4

Related Questions