[英]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();
但是如何按标题排序foos列表? 如何按标题搜索foos? 最好是使用生成的查询在数据库上完成,而不是在Eloquent集合上完成。
如果遵循Laravel中默认的多态关系数据库结构,我相信您可以使用whereHas将结果限制为仅foo实例。
我目前无法使用机器进行测试,但这是我会尝试的方法:
$items = Item::whereHas('extended' => function ($q) {
$q->where('extended_type', 'foo');
})->with('extended')->orderBy('title')->get();
要对相关表进行排序,必须首先将表连接在一起。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.