下面由Laravel教程欄目給大家介紹Laravel 子查詢語句用法,希望對需要的朋友有所幫助!
class UserController extends Controller{ public function index() { $columns = ['id', 'name', 'email', 'created_at']; $users = User::addSelect([ 'last_post_title' => Post::select(['title']) ->whereColumn('user_id', 'users.id') ->where('status', Post::STATUS_NORMAL) ->orderByDesc('created_at') ->limit(1) ])->orderByDesc('id')->paginate(20, $columns); return view('user.index', ['users' => $users]); }}
addSelect 方法可用于添加一個查詢字段到已存在的查詢實(shí)例,我們通過傳遞一個數(shù)組 —— 數(shù)組鍵是返回的查詢字段名,即 SQL 語句中的 last_post_title,數(shù)組值是對應(yīng)的子查詢邏輯,注意外鍵關(guān)聯(lián)需要通過 whereColumn 方法設(shè)置,其他和正常 Eloquent 查詢一樣。