-1

Hello I'm trying to replicate this SQL code into Laravel qBuilder but I'm not getting the result I want in the collection:

select chars.name, class.name, specs.name
FROM characters as chars 
JOIN charclasses as class
JOIN charspecs as specs
WHERE chars.class_id = class.id
AND chars.spec_id = specs.id

I get the following output:
enter image description here

Then I tried this in Laravel:

$charData = DB::table('characters')
        ->select('characters.*', 'charclasses.name', 'charspecs.name')
        ->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
        ->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
        ->orderBy('user_id', 'ASC')
        ->get();
    dd($charData);

and the result is:
enter image description here

Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • I bet you can use Eloquent and correct use of relationships, take a look at the [documentation](https://laravel.com/docs/5.6/eloquent-relationships). Good Luck! – Kyslik Aug 23 '18 at 07:50
  • I'm learning by developing something gaming related to be more motivated, haven't got to the Eloquent/relationship part yet, but I will do in the next days, thanks for the tip. – Federico Ballarino Aug 23 '18 at 07:58

1 Answers1

1

The problem is that you are selecting three fields with the same name. These fields are added to an array in the php code, but the array field is being overwritten twice because there can be no duplicate keys in an associative array. If you want to select the three names you will have to give them another name.

$charData = DB::table('characters')
    ->select('characters.*', 'charclasses.name as charclassname', 'charspecs.name as charspecname')
    ->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
    ->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
    ->orderBy('user_id', 'ASC')
    ->get();
dd($charData);
Jerodev
  • 32,252
  • 11
  • 87
  • 108