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.
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!! :)
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.– Luiz Gabriel Parreira Pereira
https://laravel.com/docs/5.8/eloquent-relationships#Eager-loading
– Mateus Junges