Auto Relationship with Laravel

5

I have the following problem when trying to make an auto relationship with Laravel 5. I want to make a user registration, where users can have other users linked, creating an authoring N x N, user_user;

The user will have a status, and this status is another model.

class User extends Authenticatable{

protected $fillable = [
    'name', 'email', 'password', 'status_id'
];

...

class Vinculo extends Model{

protected $fillable = [
    'id', 'user_id', 'vinculo_id'
];

....

class StatusUser extends Model{

protected $fillable = [ 
    'id', 'nome',       
];

..

and in my UserController I query the user with status

public function show($id){  

    $result = $this->context->with('statususers')->find($id);

...

that returns json,

{
"id": 2,
"name": "aa",
"email": "[email protected]",
"statususers": {
    "id": 2,
    "nome": "Ativo"
}

}

..

Now my question is, how to consult all the users related to a specific user, and that in the linked users can also be displayed the status of each one,

Relationship in the User class

    public function vinculos(){
    return $this->belongsToMany('App\User', 'vinculos', 'user_id', 'vinculos_id');
}

...

I modify the show method, including the relationship bindings

    public function show($id){  

    $result = $this->context->with('statususers')->with('vinculos')->find($id);

The relationship is ok, but it's not returning the statuses of the linked users, that's the problem.

{
"id": 2,
"name": "aa",
"email": "[email protected]",
"remember_token": "Y7cc9OHpKalEkKivihETU2LQeNftGWZ1hqVH0v2nM1z0DZ3dUe3emwsIDxec",
"statususers": {
    "id": 2,
    "nome": "Ativo"
},
"vinculos": [
    {
        "id": 3,
        "name": "bb",
        "email": "[email protected]",
        "pivot": {
            "user_id": 2,
            "amigo_id": 3
        }
    }
        {
        "id": 4,
        "name": "cc",
        "email": "[email protected]",
        "pivot": {
            "user_id": 2,
            "amigo_id": 3
        }
    }
]

}

This is the big question, if my related object is of the class User, because the other users do not also show their respective status objects, same as the parent record of the links? Seeing that all other attributes of the User class are displayed correctly, but the status object is missing.

Can anyone help me?

    
asked by anonymous 06.03.2016 / 19:45

3 answers

4

Maybe what you're trying to do is use nested relationship .

This is a way of bringing a relationship of the relationship through the with method.

Example: posts is related to usuários , and each user has país .

No Laravel We could do this:

 Post::with('usuario.pais')->get();

The result would be something like this representation:

[
   'id'    => 1,
   'texto' => 'Meu post',
   'usuario_id' => 1,
   'usuario' => [
      'id'   => 1,
      'nome' => 'Wallace',
      'pais_id' => 1,
      'pais' => [ 'id' => 1, 'Brasil',]
   ]

]

Another detail. I forgot to mention that you should not use with methods in sequence, because internally they do not use $this to refer to the instance itself, but use new static (I already looked at source code of class Illuminate\Database\Eloquent\Model ).

You must pass all arguments at once to with , and it must also be the first one to be called.

Example (certain):

 Post::with('comments.people', 'images')->where('id', '=', 1);

 Post::with(['comments.people', 'images'])->where('id', '=', 1);

Examples (wrong):

 // isso anula a query anterior

 Post::where('id', '=', 1)->with('comments.people', 'images');


// isso só faz funcionar o último with

Post::with('comments.people')->with('images');

Other methods such as where , lists , get , and the like, are of class Illuminate\Database\Eloquent\Builder . They are called by the magic method __call present in class Model (its alias is Eloquent ). Since the with method is a static method, therefore, it only serves to create a new instance of the model itself with the relationships that will be loaded pre-defined.

To show that I am not giving any incorrect information, just check the code in github , on line 672 .

link

    
09.03.2016 / 14:14
1

Good afternoon guys, So Wallace, that was not quite what I wanted, but I've been able to solve it.

09.03.2016 / 15:48
1

Just make a hasMany .

Example: I am a person and have several children, my dependents who are people ..

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Pessoa extends Model
{
  // id, usuario_id, nome, rg, cpf, foto_url, data_nascimento, endereco_id, responsavel_id, fornecedor_id

  protected $fillable =
  ['usuario_id', 'nome', 'rg', 'cpf', 'foto_url', 'data_nascimento', 'responsavel_id', 'fornecedor_id'];

  public $timestamps = false;


  public function dependentes()
  {
    return $this->hasMany('App\Pessoa','responsavel_id');
  }

  public function contatos()
  {
    return $this->hasOne('App\Contato');
  }

}
    
27.08.2016 / 18:37