Larval Relationsships 5.4

Asked

Viewed 46 times

2

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

My question is: How do I relate the 3 tables to the with() method where (Where()) user this login would be equal to the id of the Users table and get all information from the Departments and Posts table?

OBS(I have the hasMany methods and also by the inverse belongstoMany) More as I apply this logic?

  • Put your models?

  • If you can solve it here?

  • 1

    Yes. Sorry for the delay in answering Virgilio. Thank you very much for your attention

1 answer

1


I couldn’t quite understand the question, but I believe your code should be like this:

Users.php

<?php

namespace App;

// ignorado...

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

Departamento.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 so:

$departamentos = auth()->user()->departamentos; // departamentos do usuario logado...
$postagens = $departamentos->postagens; // postagens desse departamento...
  • So I had all my relationships done. However, here’s what’s picking up. have this method in Department public Function postagems() { Return $this->hasMany(Post::class, 'department_id'); } >postagems More error happens Property [postagems] does not exist on this Collection instance. I wonder what’s going on?

  • So what’s the problem? I haven’t been able to capture it yet. :(

  • Like everything you’ve done, this one except the part where I call the $departments->posts, there’s an error. What could it be? The error and that Property [postagems] does not exist on this Collection instance.

  • In my Department Model I have the public method works posts returning this->hasMany(Post::class);

  • You say the mistake is: Property [postagems] with M and its method is set as public function postagens() with N. Check it out there.

  • All right, but even so does not access. even though public Function psotagens() and I calling $departments->posts; it gives the same error. : ( One more thing I didn’t know and that we could access by the logged-in user auth()->user()->departments . But only that question is missing here that is not calling in the controller.

Show 1 more comment

Browser other questions tagged

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