I've implemented single table inheritance using Eloquent models and now I want to be able to sort and search the database based on the parent model and the child model. I've used polymorphic relations to accomplish this.
The base model only has the morphing method.
class Item extends Model
{
public function extended()
{
return $this->morphTo();
}
}
All models that extends the item has some basic properties
abstract class ExtendedItem extends Model
{
/**
* The relationships to always load with the model
*
* @var array
*/
protected $with = ['item'];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['title'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['item'];
public function getTitleAttribute()
{
return $this->item->title;
}
public function item()
{
return $this->morphOne('App\Item', 'extended');
}
}
Example child classes
class Foo extends ExtendedItem
{
public function bars()
{
return $this->hasMany('App\Bar')->orderBy('bar_col1')->orderBy('bar_col2');
}
}
class Bar extends ExtendedItem
{
public function foo()
{
return $this->belongsTo('App\Foo');
}
}
If I want to list all the items I use $items = Item::with('extended')->get();
and if I only want the Foo objects I use $foos = Foo::all();
.
I can order a list of all items using
$items = return Item::with('extended')->orderBy('title')->get();
but how can I order a list of foos by title? How can I search foos by title? Preferably this would be done on the database with a generated query and not done on an Eloquent collection.