pmiranda
pmiranda

Reputation: 8450

Eloquent in Laravel-Datatables, select in select?

I have 3 tables, the 1st has a FK from the 2nd, and the 2nd has a FK from the 3rd:

Table 1: [admin_demandas]
-------------------------
id_demanda|   projec_id
-------------------------

Table 2: [admin_projec]
-------------------------
id_projec |   sub_id
-------------------------

Table 3: [admin_sub]
-------------------------
id_sub    |   name
-------------------------

What I need is to get the 'name' from Table 3 but starting with the Model of the table 1.

I was trying something like this:

$data = AdminDemanda::select([
    'id_demanda',
    'admin_projec.sub_id AS sub_id',
    'admin_sub.name AS name',])
    ->join('admin_projec', 'admin_demandas.projec_id', '=', 'admin_projec.id_projec')
    ->join('admin_sub', 'admin_projec.sub_id', '=', 'admin_sub.id_sub')
    ->get();

return Datatables::of($data)->make(true);

I've done my Datatables with only 1 JOIN (2 tables) but not sure how to do those 2 JOIN (3 tables). I got this error:

[Err] 1054 - Unknown column 'admin_projec.sub_id' in 'on clause'

What should I modify in my query? Should I need to use query builder instead Eloquent, with a DB::raw() query?

Upvotes: 0

Views: 1550

Answers (2)

pmiranda
pmiranda

Reputation: 8450

Solved with this:

Inner join between three tables in mysql

it was simple... now in case anyone need it, my Datatable query is:

$datos = AdminDemanda::select([
    'id_demanda',
    'admin_dis.nombre AS nombre_dist',
    'admin_sub.nombre AS nombre_subes',
    'mes AS mes_demanda',
    'admin_sistemas.nombre AS nombre_sistema',
    'admin_demandas.demanda_mwh AS mwh'])
    ->join('admin_projec', 'admin_demandas.proyeccion_demanda_id', '=', 'admin_projec.id_proyeccion_demanda')
    ->join('admin_sub', 'admin_projec.subestacion_id', '=', 'admin_sub.id_subestacion')
    ->join('admin_dis', 'admin_projec.dist_id', '=', 'admin_dis.id_dist')
    ->join('admin_sistemas', 'admin_projec.sistema_id', '=', 'admin_sistemas.id_sistema')
    ->get();

Upvotes: 1

Atnaize
Atnaize

Reputation: 1816

You should edit your models

By exemple in AdminSub model

public function projec(){
    return $this->hasMany(AdminProjec::class , 'sub_id');
}

You should be able to do

\AdminSub::first()->projec();

And continue by editing your AdminProjec model with the same kind of relationship

public function demandas(){
    return $this->hasMany(AdminDemandas::class , 'projec_id');
}

And now you could try

//I do not remember which one will works
\AdminSub::first()->projec()->first()->demandas()->name
//or 
\AdminSub::first()->projec()->first()->demandas()->get()->name 

Upvotes: 0

Related Questions