0

我正在使用 Laravel 4 并返回一个 belongsToMany 关系

我的模特

class User extends SentryUserModel implements PresentableInterface {
  public function getPresenter() {
    return new UserPresenter($this);
  }

  public function tweak() {
    return self::results();
  }

  public function tweakTwo() {
    return self::results()->get();
  }

  public function results() {
    return $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id');
  }
}

我的控制器

$user->tweak是一个对象(Illuminate\Database\Eloquent\Collection)

foreach($user->tweak as $twk) {
}

$user->tweakTwo()是一个对象(Illuminate\Database\Eloquent\Collection)不带括号不起作用

foreach($user->tweakTwo as $twk) {
  // this results an error Call to undefined method Illuminate\Database\Eloquent\Collection::getResults()
  // this only works if I use $user->tweakTwo()
}

为什么 $user->tweakTwo 需要括号?


编辑跟进问题

  public function tweakTwo() {
    $result_one = self::results()->get();
    $result_two = self::results_two()->get();
    return $result_one->merge($result_two);
  }

我怎样才能重新打包它,以便我可以调用 $user->tweakTwo 而不是 $user->tweakTwo()

4

1 回答 1

2

因为你已经在做不带括号的调用了。

$user->tweak === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get();
$user->tweak() === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id');

如果你这么说

$user->tweakTwo() === self::results()->get() === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get();

然后

$user->tweakTwo() === $user->tweak

$user->tweakTwo

将会

$this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get()->get();
于 2013-07-25T01:09:42.950 回答