鍍金池/ 問答/PHP/ 優(yōu)化一下 laravel 的查詢語句

優(yōu)化一下 laravel 的查詢語句

圖片描述

回答
編輯回答
殘淚

去掉后面整個orWher,只考慮一個條件的情況下(紅框內(nèi)有兩個),把pub_time那個條件當(dāng)作a,閉包內(nèi)的short_time當(dāng)作c,相當(dāng)于a ||(a&c),最后的結(jié)果取決與a,a為true(查詢的到的話),結(jié)果為ture,false則結(jié)果為false,所以等價于a||(a&c) = a

2017年6月17日 03:50
編輯回答
任她鬧

如果僅僅解決你框中重復(fù)的問題,一下代碼足夠了

$data2 = DB::table('jtgw_oarea as a')->leftJoin('jtgw_oarea_type as c', 'a.tid','=','c.id')
                    ->leftJoin('jtgw_oarea_content as t', 'a.id','=','t.cid')
                    ->select($field)
                    ->where('pub_time','<=',time())
                    ->where('a.is_delete','=',1)
                    ->where(function($query) use ($search) {
                        $query->where('a.title', 'like', '%'. $search.'%')
                              ->orWhere('a.short_title', 'like', '%'. $search.'%'); 
                    })
                    ->orderBy('a.pub_time','desc')
                    ->get()
                    ->toArray();
2017年7月12日 12:04
編輯回答
浪婳

如果你有三個模型相關(guān)聯(lián),那么這一行代碼
DB::table('jtgw_oarea as a')->leftJoin('jtgw_oarea_type as c', 'a.tid','=','c.id') ->leftJoin('jtgw_oarea_content as t', 'a.id','=','t.cid')
就等價于
jtgw_oarea::with('jtgw_oarea_type','jtgw_oarea_content')
這一行代碼
且where('a.is_delete', '=', 1)也可以寫成where('a.is_delete', 1)
且where('a.title', 'like', '%'. $search.'%')也可以寫成where('a.title', 'like', "%$search%")

2017年1月7日 16:31
編輯回答
夏木

建立模型關(guān)聯(lián),然后再輔以合適的scope封裝,代碼應(yīng)該可以優(yōu)雅很多,由于不知道你系統(tǒng)里的有哪些模型和模型之間的關(guān)系,所以無法給出具體的優(yōu)化方案。如果給出模型以及之間的關(guān)系,可以優(yōu)化。

2017年4月17日 08:19
編輯回答
魚梓
$data2 = DB::table('jtgw_oarea as a')->leftJoin('jtgw_oarea_type as c', 'a.tid','=','c.id')
                    ->leftJoin('jtgw_oarea_content as t', 'a.id','=','t.cid')
                    ->select($field)
                    ->where('pub_time','<=',time())
                    ->where('a.is_delete','=',1)
                    ->where(function($query) use ($search) {
                        $query->where('a.title', 'like', '%'. $search.'%')
                              ->orWhere('a.short_title', 'like', '%'. $search.'%'); 
                    })
                    ->orderBy('a.pub_time','desc')
                    ->get()
                    ->toArray();
2017年1月12日 02:30