0

I am using Laravel 4 and returning a belongsToMany relationship

MY MODEL

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

MY CONTROLLER

$user->tweak is a object(Illuminate\Database\Eloquent\Collection)

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

$user->tweakTwo() is a object(Illuminate\Database\Eloquent\Collection) does not work without parenthesis

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()
}

Why does $user->tweakTwo require the parenthesis?


edit follow up question

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

How could I re-package it so that I can call $user->tweakTwo instead of $user->tweakTwo()

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
user391986
  • 29,536
  • 39
  • 126
  • 205

1 Answers1

2

Because you're already doing what a call without parenthesis does.

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

and if you say that

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

then

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

and

$user->tweakTwo

would be

$this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get()->get();
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • ah thanks alot for the great explanation Antonio. I have one follow up question I would like your input, I've edited the question. You see the reason I call ->get() from within my model is that I need to merge two data sets as shown in the edit, is there a way I could re-package the result of the merge so that I can use this attribute in format $user->tweakTwo ? I guess the question ends up being can I re-convert a Collection back to a QueryBuilder – user391986 Jul 25 '13 at 02:18
  • I don't think you can, a QueryBuilder instance is basically a bunch of sql (or not) query parts not yet glued (select foo from bar...), so, transform a single result set (collection) back to a query, at least to me, would something very difficult, now think about two. :) IMHO, your best bet is some kind of join or union in this case. – Antonio Carlos Ribeiro Jul 25 '13 at 13:56