duanniesui6391 2016-03-23 12:30
浏览 54

使用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.

  • 写回答

2条回答 默认 最新

  • dongshiru5913 2016-03-23 12:54
    关注

    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();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?