Reputation: 25549
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.
Upvotes: 0
Views: 1314
Reputation: 4988
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;
Upvotes: 1
Reputation: 25549
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.
Upvotes: 0