我已經使用Eloquent模型實現了單表繼承,現在我希望能夠根據父模型和子模型對數據庫進行排序和搜索。我用polymorphic relations來實現這一點。使用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集合上完成。
我猜你的意思是'項目:: whereHas( '擴展',函數($ Q){...}) - >與... '。這給了我一個錯誤,說'在'where子句'...'中未找到列:1054未知列'self_18aab6fab05a597f53c25ac6f61ae312.id',並且每次刷新都會更改表名。 –
的確,這是我的一個錯字。就像我說的,我現在無法測試它,所以我不確定它是否有效,但這是我首先嚐試的。) – Vercoutere