How can I list 3 tables using Laravel

Asked

Viewed 505 times

0

Hello, I need some help with Relationships.

I’m studying Laravel and I came across this problem.

I could use Join, but wanted a simpler way and use Laravel’s relationships to do this kind of search.

I have 3 tables according to image.

Tables

I’m willing to do a following search.

Cargo::find(2)->colaborador->user;

Find all users whose job is id 2.

That way it didn’t work.


Cargo::find(2)->colaborador;

This one works.

Search all the collaborators I need, but this table has only FK. So I can’t get name, email, etc.


Below I put my simplified models only with the grating between the tables I made.

I might be wrong in the relationship too.

Colaborador Model.

<?php
class Colaborador extends Model
{
    protected $table = "colaboradores";
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function cargo()
    {
        return $this->belongsTo(Cargo::class);
    }
}

Cargo Model

<?php
class Cargo extends Model
{
    protected $table = "cargos";
    public function colaborador()
    {
        return $this->hasMany(Colaborador::class);
    }
}

User Model

<?php
class User extends Authenticatable
{
    use Notifiable;
    public function colaborador()
    {
        return $this->hasOne(Colaborador::class);
    }

}

Thanks in advance!! :)

1 answer

1


Just make the following Relations:

In the collaborating model:

 class Colaborador extends Model
    {
        protected $table = "colaboradores";

        public function user()
        {
            return $this->belongsTo(User::class, 'user_id');
        }
    }

In the role model:

class Cargo extends Model
{
    protected $table = "cargos";

    public function colaboradores()
    {
        return $this->hasMany(Colaborador::class, 'cargo_id');
    }
}

After you set the Relations, you can query them as follows:

Cargo::find(2)->colaboradores()->with('user)->get();

You’ll get your relationship back colaboradores and, on the brim relations, appears the user related to this model of collaborators, more or less like this:

Collection {#214 ▼
  #items: array:1 [▼
    0 => Colaborador {#209 ▼
      #fillable: array:2 [▶]
      #connection: "pgsql"
      #table: "colaboradors"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:5 [▼
        "id" => 1
        "user_id" => 1
        "cargo_id" => 1
        "created_at" => "2019-05-24 01:34:33"
        "updated_at" => "2019-05-24 01:34:33"
      ]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "user" => User {#222 ▼
          #fillable: array:3 [▶]
          #hidden: array:2 [▶]
          #casts: array:1 [▶]
          #connection: "pgsql"
          #table: "users"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:8 [▼
            "id" => 1
            "name" => "Nome do usuario"
            "email" => "[email protected]"
            "email_verified_at" => null
            "password" => "password"
            "remember_token" => null
            "created_at" => "2019-05-24 01:32:03"
            "updated_at" => "2019-05-24 01:32:03"
          ]
          #original: array:8 [▶]
          #changes: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #visible: []
          #guarded: array:1 [▶]
          #rememberTokenName: "remember_token"
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
  ]
}

To access the user in Relationship, just use a repeat loop:

foreach($colaboradores as $colaborador){
    $user = $colaborador->user;
    //
}
  • It worked perfectly. But I’d like to know where I can find more about this with(). Cargo::find(2)->colaboradores()->with('user)->get(); I couldn’t find it in the documentation, I couldn’t find it in either Builder or Relationships.

  • https://laravel.com/docs/5.8/eloquent-relationships#Eager-loading

Browser other questions tagged

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