Inner Join Laravel

Asked

Viewed 180 times

0

I am trying to select data from the module table through relationship in the Standard. Where I have 2 tables Module and Activities In activity I have id_modulo and I need to select a column called module title through id.

$status = DB::table('atividades')
            ->join('modulos', function ($join) {
                $join->on('modulos.id', '=', 'atividades.id_modulo');
            })
            ->select('modulos.*')
            ->get();
       $status = $status->titulo;

This script returns me empty array.

  • Which version of the Laravel you are using ?

  • In the bank there really are records and are related correctly?

  • If there is more than one record in the query you must recover the value per array, if you wanted the first record, use ->get()[0] or ->first()

  • @Pedrohenrique version 5.8

  • @Kayobruno yes the bank has normal relationship between the tables.

  • 1

    There is only one modulos.id for a atividades.id_modulo ?

  • Yes, @Pedrohenrique

  • @Richardnicson Pq not use the Eloquent of the Laravel?? The Eloquent will provide you with means to access this information without having to do Join

Show 3 more comments

1 answer

1


  • When using the first(), you recover the first line of your query SQL, ideal for queries that will return only one result.
  • When using the get(), you recover all the query lines. (Remember that you need to loop the return to access all the lines, even if there is only one result or inform which position you want to recover).

In your case you’re using the get() to bring your consultation result, as the get() returns an array needs to be dealt with before recovering the value, otherwise you will receive some errors, see the examples below.

  • In this case the ideal would be to use the method first() which will return the first result of the query.

    $status = DB::table('atividades')
                ->join('modulos', 'modulos.id', '=', 'atividades.id_modulo')
                ->select('modulos.*')
                ->first();
    $status = $status->titulo;
    
  • In case you wanted to continue using the method get(), before recovering the value of any column, you must inform that you want to access the first position of the return.

    $status = DB::table('atividades')
                ->join('modulos', 'modulos.id', '=', 'atividades.id_modulo')
                ->select('modulos.*')
                ->get();
    $status = $status[0]->titulo;
    

Reference: Database: Query Builder

Browser other questions tagged

You are not signed in. Login or sign up in order to post.