使用Eloquent对单个表继承结构进行排序和搜索


Sorting and searching a single table inheritance structure with Eloquent

我已经使用Eloquent模型实现了单表继承,现在我希望能够根据父模型和子模型对数据库进行排序和搜索。我已经使用多态关系来实现这一点。

基础模型只有变形方法。

class Item extends Model
{
    public function extended()
    {
        return $this->morphTo();
    }
}

所有扩展项目的模型都具有一些基本属性

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

示例子类

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

如果我想列出所有项目,我使用$items = Item::with('extended')->get();,如果我只想要Foo对象,我使用$foos = Foo::all();


我可以使用订购所有项目的列表

$items = return Item::with('extended')->orderBy('title')->get();

但是我怎样才能按标题排序foo列表呢?如何按标题搜索foos?优选地,这将通过生成的查询在数据库上完成,而不是在Eloquent集合上完成。

若要对相关表进行排序,必须首先联接该表。

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

可以使用whereHas 进行搜索

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

如果遵循Laravel中多态关系的默认数据库结构,我相信您可以使用whereHas将结果限制为仅foo实例。

我现在没有机器可以测试,但这是我想尝试的:

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