[英]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.