下面由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 方法可用于添加一个查询字段到已存在的查询实例,我们通过传递一个数组 —— 数组键是返回的查询字段名,即 sql 语句中的 last_post_title,数组值是对应的子查询逻辑,注意外键关联需要通过 wherecolumn 方法设置,其他和正常 eloquent 查询一样。
以上就是介绍Laravel子查询语句用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号