简体   繁体   中英

Sorting and searching a single table inheritance structure with Eloquent

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.

If following the default database structure for polymorphic relations in Laravel, I believe you can use whereHas to limit your results to only foo instances.

I don't have access to a machine to test right now, but this is what I would try:

$items = Item::whereHas('extended' => function ($q) {
    $q->where('extended_type', 'foo');
})->with('extended')->orderBy('title')->get();

To sort the related table, the table must first be joined.

return Foo::with('item')
    ->join('items', 'items.extended_id', '=', 'foos.id')
    ->orderBy('title', 'DESC')
    ->get();

Searching can be done using whereHas

return Foo::whereHas('item', function ($q) {
    $q->where('title', 'LIKE', '%baz%');
})->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM