RelationsShips Larval 5.4

2

I have 3 tables, [Users - > Departments - > Postings] where the Users table has many Departments Departments have many Postings.

My question is: How do I relate the 3 tables with the with () method where (where () () is this logged in would equal the id of the Users table and get all information from the Departments and Postings table? >

    
asked by anonymous 23.08.2017 / 19:42

1 answer

1

I could not quite understand the issue, but I think your code should look like this:

Users.php

<?php

namespace App;

// ignorado...

class User extends Authenticatable
{
    // ignorado...
    public function departamentos()
    {
        return $this->hasMany(Departamento::class);
    }
}

Department.php

<?php

namespace App;

// ignorado...

class Departamento extends Model
{
    // ignorado...
    public function postagens()
    {
        return $this->hasMany(Postagem::class, 'departamento_id');
    }
}

Post.php

<?php

namespace App;

// ignorado...

class Postagem extends Model
{
        // ignorado...
}

Having these 3 files, in your controller you could do this:

$departamentos = auth()->user()->departamentos; // departamentos do usuario logado...
$postagens = $departamentos->postagens; // postagens desse departamento...
    
23.08.2017 / 19:56