直接上代碼
$result = User::with('topics:user_id,body,title') ->where('name', 'Summer') ->get() ->toArray();
如果要進行約束預加載,應該這樣寫。
$result = User::with(['topics' => function ($query) { $query->select('id', 'user_id', 'body', 'title') ->orderBy('updated_at', 'desc'); }]) ->where('name', 'Summer') ->get() ->toArray();
在使用預加載時,表的關聯字段一定要查詢,否則查詢后的數據沒法匹配