Eloquent: Relationship (JSON) -> Hasmany and Belongsto

Asked

Viewed 167 times

0

Say guys all right?

Next, I have a little problem related to two models within my project.

First Model I have a relationship hasOne:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $with = ['phone'];

    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

In the second Model I do the reverse relationship BelongsTo:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    protected $with = ['user'];

    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

When I add the protected $with, put together to return the relationship, is on a loop and does not process.

Who can give me a light for it to return both the normal relationship as well as the reverse?

My return when I take the user route is:

{
   "id":1,
   "email":"[email protected]",
   "phone":{
      "id":1,
      "phone":"123456",
      "user_id":1,
      "user":{
         "id":1,
         "email":"[email protected]",
         "phone":{
            "id":1,
            "phone":"123456",
            "user_id":1,
            "user":{
               "id":1,
               "email":"[email protected]",
               "phone":{
                  "id":1,
                  "phone":"123456",
                  "user_id":1,
                  "user":{
                     "id":1,
                     "email":"[email protected]",
                     "phone":{
                        "id":1,
                        "phone":"123456",
                        "user_id":1,
                        "user":{
                           ... /*infinito*/
                        }
                     }
                  }
               }
            }
         }
      }
   }
}
  • Ueh what is the relationship? You are confused if you are asking one and talking about another

  • Virginio, I edited the question by placing the return and showing the moment when it is in infinite loop.

  • Take $with first

2 answers

0

Yes, because whenever you call user, you call phone and whenever phone calls user, that calls phone...

You can take the:

protected $with = ['user'];

And just use the relationship normally when you need to use the phone:

$user->telefone; 

If you want $with, remove the $with from the phone that will stop your loop, just leave it on the user. I particularly prefer not to use $with;

0

protected $with = ['user'];

tries to rotate without the $with and call him when you wish

$variavel->telefone ou $variavel->telefone()

Browser other questions tagged

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