You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用withExists查询时read_exists列报错,如何指定字段查询?

Laravel查询报错:unknown column read_exists 解决方法

你遇到的问题根源在于:read_exists是withExists方法动态生成的虚拟字段,并非用户表中实际存在的数据库列,所以直接把它放进select数组里会触发列不存在的错误。

下面是两种可行的解决方式:

方式一:利用Eloquent自动附加虚拟字段

withExists会自动将生成的read_exists字段附加到查询返回的模型实例上,你只需要指定用户表中实际存在的字段即可:

User::whereIn('id', $ids)
    ->withExists(['read' => function($q) use($post) {
        $q->where('post_id', $post->id);
    }])
    ->select(['id', 'user_name']) // 仅选择数据库中真实存在的字段
    ->get();

注:建议保留id字段,Eloquent模型依赖主键来维护实例的完整性,避免后续操作出现意外问题。

方式二:用selectRaw手动构造存在性判断

如果需要直接在SQL层面控制字段输出,可以用selectRaw替代withExists,手动编写存在性查询:

User::whereIn('id', $ids)
    ->select([
        'user_name',
        DB::raw('EXISTS(SELECT 1 FROM reads WHERE reads.user_id = users.id AND reads.post_id = ?) as read_exists', [$post->id])
    ])
    ->get();

注意:将reads替换为你实际的关联表名称,确保表名和字段关联关系正确。

内容的提问来源于stack exchange,提问作者Klick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:55:22