简体   繁体   中英

Laravel 4 / Eloquent ORM: Is it possible to obtain the object behind a relation?

Assuming I have these two classes:

class User extends Eloquent
{
    public function phone()
    {
        return $this->hasMany('phone');
    }
}
class Phone extends Eloquent
{
    public function user()
    {
        return $this->belongsTo('user');
    }
}  

(Relationships aren't necessarily presented in this way.)

I'm trying to achieve this by using accessors :

class Phone extends Eloquent
{
    public function user()
    {
        return $this->belongsTo('user');
    }
    public function getNumberAttribute($value)
    {
        //Grant access to the User object who has this Phone.
        $userWhoOwnsThisPhoneNumber = /*SOMETHING*/;

        /*For example, $userWhoOwnsThisPhoneNumber->phone should return THIS phone object.  */
        //...

    }
}  

Then perhaps do something like this:

$user = User::find($id)->phone->number;

I skimmed through the documentations multiple times, I couldn't find anything useful. Is it possible to do such as thing with Laravel 4?

Because you might have more than one phone for each user, your relations should be:

class User extends Eloquent
{
    public function phones() /// <--- this is just to be clearer
    {
        return $this->hasMany('phone');
    }
}

class Phone extends Eloquent
{
    public function user()
    {
        return $this->belongsTo('user');
    }
}  

And you don't need any acessors, unless you need to change anything in the number, so you can just:

$user = User::find($id);
$phones = $user->phones;

foreach ($phones as $phone)
{
  echo $phone->user->name;
}

or just

foreach (User::find($id)->phones as $phone)
{
  echo $phone->user->name;
}

And you can also

$phone = Phone::where('number','555-5050')->first();
echo $phone->user->name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM