2016-04-19 279 views
1

我有3個系列合併在我的controller中,我的問題是我希望合併的集合按expiry_date排序。Laravel排序合併集合

$expiry = date('Y-m-d', strtotime('+3 months')); 
    $servers = Server::where('expiry_date', '<', $expiry)->orderBy('expiry_date', 'asc')->get(); 
    $domains = Domain::where('expiry_date', '<', $expiry)->orderBy('expiry_date', 'asc')->get(); 
    $hosts = Host::where('expiry_date', '<', $expiry)->orderBy('expiry_date', 'asc')->get(); 
    $invoices = $domains->merge($servers)->merge($hosts); 
+0

剛一說明:我會成爲一個包含'scopeExpiresAfter性狀($查詢,DateTimeInterface $日期)'方法,可以應用到你的'Server','Domain'和'Host'楷模。然後這會清除你的代碼:'Server :: expiresAfter($ threeMonths) - > get()'。 –

回答

0

使用SQL查詢解決,萬一有人正在尋找類似的東西。

$servers = DB::table('servers')->select(DB::raw('"Server" as type, servers.id, servers.client_id, servers.expiry_date, servers.name, clients.name as clientName'))->leftJoin('clients', 'servers.client_id', '=', 'clients.id')->where('expiry_date', '<', $expiry); 
    $domains = DB::table('domains')->select(DB::raw('"Domain" as type, domains.id, domains.client_id, domains.expiry_date, domains.name, clients.name as clientName'))->leftJoin('clients', 'domains.client_id', '=', 'clients.id')->where('expiry_date', '<', $expiry); 
    $hosts = DB::table('hosts')->select(DB::raw('"Host" as type, hosts.id, hosts.client_id, hosts.expiry_date, hosts.name, clients.name as clientName'))->leftJoin('clients', 'hosts.client_id', '=', 'clients.id')->where('expiry_date', '<', $expiry)->unionAll($domains)->unionAll($servers)->orderBy('expiry_date', 'asc')->get();   
1

如果orderBy()工作正常您的查詢中,這應該爲你工作:

$expiry = date('Y-m-d', strtotime('+3 months')); 
$servers = Server::where('expiry_date', '<', $expiry)->get(); 
$domains = Domain::where('expiry_date', '<', $expiry)->get(); 
$hosts = Host::where('expiry_date', '<', $expiry)->get(); 
$invoices = $domains->merge($servers)->merge($hosts); 
$invoices->sortBy('expiry_date'); 
+0

'orderBy()'工作正常,但這不起作用 – dev7

+0

你有任何錯誤?如果不是,那究竟是行不通的? –

+0

'asort()期望參數2長,字符串給定'我嘗試沒有asc,沒有錯誤,但它沒有排序 – dev7