0
votes

DB structure:

items ( id, ... )
photos ( id, ... )
comments ( id, entity_id, entity_type )

where entity_type is an ENUM ('Item', 'Photo')

Models:

class Item extends Eloquent {
  public function comments() {
    return $this->morphMany('Comment', 'entity');
  }
}
class Photo extends Eloquent {
  // same as Item
}
class Comment extends Eloquent {
  public function entity() {
    return $this->morphTo();
  }
}

For some reason when I try this:

$comments = $item->comments()->orderBy('created_at', 'asc')->get();

I get this error.

Call to undefined method Illuminate\Database\Query\Builder::getMorphClass()

It seems like it's trying to use the Query Builder instead of MorphOneOrMany, which does have getMorphClass defined. But even if I simply do $item->comments without any further query building, it gives the same error.

2
What version of the framework? - Jarek Tkaczyk
@JarekTkaczyk Not sure, but I started this project 7-8 months ago. But I was looking at the latest version documentation when I added the morph stuff above, so it was probably out of date by then. Updated the framework and it seems to be working. That was a nice use of 100 reputation -_- - andrewtweber
You can see the version number in your composer.json file - mydoglixu

2 Answers

1
votes

Here's the documentation on Polymorphic relations: http://laravel.com/docs/4.2/eloquent#polymorphic-relations

If I understand correctly, a comment can be used on an Item or a Photo. The models you pasted were setup correctly for that.

In order to sort relationships you can use a closure like this:

$item = Item::with(array('comments' => function ($query) {
    $query->orderBy('created_at');
}))->find($id);

// These will be sorted:
$item->comments;
0
votes

Here is my temporary solution

class Item extends Eloquent {
  public function comments() {
    return $this->hasMany('Comment', 'entity_id')
      ->where('entity_type', '=', 'Item');
  }
}

I would really prefer to use morphMany though.