5
I have the following problem trying to make a self relationship with Laravel 5. I want to make a user registration, where users may have other users linked, creating an autorelationing 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 the json,
{
"id": 2,
"name": "aa",
"email": "[email protected]",
"statususers": {
"id": 2,
"nome": "Ativo"
}
}
..
Now my question is, how to query all users related to a specific user, and that on linked users can also be displayed the status of each,
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 links
public function show($id){
$result = $this->context->with('statususers')->with('vinculos')->find($id);
Relationship is ok, but is not returning the status of linked users, this is 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 User class, why do not other users also show their respective status objects, equal to 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 someone help me?
But you force the load of relationships by doing the way I did. I don’t understand what’s wrong with my answer. You showed your json, but you didn’t show how you got the result. It’s good to post here so others understand how you solved the problem.
– Wallace Maxters
I won’t take the negative until I have the real solution to the problem. Demonstrate how the expected return of the data is not the solution of the problem, you need to show the code with which you arrived at it.
– Wallace Maxters