0

假设我有这两个类:

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

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

我试图通过使用访问器来实现这一点:

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 做这样的事情吗?

4

1 回答 1

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;
于 2013-09-19T16:15:56.897 回答