2016-03-23 56 views
0

我已經使用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集合上完成。

回答

0

如果按照在Laravel多態性關係的默認數據庫結構,我相信你可以使用whereHas來限制你的結果只有FOO實例。

我沒有獲得一臺機器,現在來測試,但是這是我想嘗試:

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

我猜你的意思是'項目:: whereHas( '擴展',函數($ Q){...}) - >與... '。這給了我一個錯誤,說'在'where子句'...'中未找到列:1054未知列'self_18aab6fab05a597f53c25ac6f61ae312.id',並且每次刷新都會更改表名。 –

+0

的確,這是我的一個錯字。就像我說的,我現在無法測試它,所以我不確定它是否有效,但這是我首先嚐試的。) – Vercoutere

0

排序相關的表,該表必須首先加入。

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(); 
相關問題