Laravel 4 / Eloquent ORM:是否有可能获得关系背后的对象?

时间:2013-09-19 15:59:47

标签: php laravel laravel-4 eloquent

假设我有这两个类:

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

(关系不一定以这种方式呈现。)

我正在尝试使用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.  */
        //...

    }
}  

然后也许做这样的事情:

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

我多次浏览文档,找不到任何有用的东西。是否有可能像Laravel 4那样做?

1 个答案:

答案 0 :(得分:0)

因为每个用户可能有多个电话,所以您的关系应该是:

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');
    }
}  

除非您需要更改号码中的任何内容,否则您不需要任何访问者,所以您可以:

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

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

或只是

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

你也可以

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