2017-08-25 59 views
0

如何適用於雄辯的查詢與「hasOne」關聯關係表排序?在Laravel使用排序查詢口才

品牌型號

class Brand extends Eloquent 
{ 
    protected $table = 'brand'; 
    protected $primaryKey = 'id'; 
    protected $fillable = ['brand_name']; 
    public $sortable = ['brand_name']; 

    public function brandModel() { 
     return $this->hasOne('App\Brandmodel', 'brand_id') 
         ->select('id', 'brand_id', 'brand_model_name'); 
    } 
} 

--------------------------------------- 

class Brandmodel extends Eloquent 
{ 
    protected $table = 'brandmodel'; 
    protected $primaryKey = 'id'; 
    protected $fillable = ['brand_id']; 
    public $sortable = ['brand_model_name']; 
} 

在這種情況下,我們可以使用排序 「BRAND_NAME」。但是我不能夠使用「brand_model_name」進行排序。

回答

0

如果你想這樣做,你就需要加強口才之外一點點,並加入你所需要的表。

Brand::join('brandmodel', 'brandmodel.brand_id', '=', 'brand.id') 
    ->orderBy('brandmodel.brand_model_name') 
    ->get(); 

我也建議你重新工作,你的表名稱相匹配雄辯的默認命名慣例,因爲這將使得代碼更容易一些解析。

+0

嗨,感謝您的回覆,但我期待能用「充分雄辯」 – Franklin

+0

這只是使用Eloquent的查詢生成器來加入表格,使用您設置的關係方法無法做到這一點。這是因爲「Eloqent-LY」,你會得到它。 – Dwight

0

你應該嘗試這可能對您的工作:

Brand::leftJoin('brandmodel', 'brandmodel.brand_id', '=', 'brand.id') 
    ->orderBy('brandmodel.brand_model_name','desc') 
    ->get(); 

希望對你這個解決方案的工作!