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

如何无需手动指定字段,构建Eloquent查询过滤空值字段?

自动过滤所有NULL字段的Eloquent查询方案

方法一:动态获取表字段构建查询

利用Laravel的Schema类获取目标表的所有字段名,再循环给查询添加whereNotNull条件,不用手动逐个指定字段:

use Illuminate\Support\Facades\Schema;

// 替换成你的模型类,比如Post
$model = new Post();
$tableName = $model->getTable();
$columns = Schema::getColumnListing($tableName);

$query = $model->query();
foreach ($columns as $column) {
    $query->whereNotNull($column);
}

// 获取所有字段均非空的记录
$results = $query->get();

方法二:封装为模型全局作用域(复用场景)

如果需要频繁使用这个查询逻辑,可以给模型添加全局作用域,让每次查询自动应用非空过滤:

// 在你的模型文件(如Post.php)中
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class Post extends Model
{
    protected static function booted()
    {
        static::addGlobalScope('all_fields_not_null', function (Builder $builder) {
            $columns = Schema::getColumnListing($builder->getModel()->getTable());
            foreach ($columns as $column) {
                $builder->whereNotNull($column);
            }
        });
    }
}

之后直接调用Post::get()就会自动返回所有字段非空的记录;若临时需要取消该约束,可使用:

// 跳过全局作用域,查询包含NULL字段的所有数据
$results = Post::withoutGlobalScope('all_fields_not_null')->get();

额外说明

  • 上述逻辑会筛选出所有字段均非空的记录,完全匹配“获取已填充列数据”的需求。
  • 若存在允许为NULL的字段,可在循环时排除:
// 示例:排除允许为NULL的字段
$excludeColumns = ['created_at', 'updated_at'];
foreach ($columns as $column) {
    if (!in_array($column, $excludeColumns)) {
        $query->whereNotNull($column);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:25:54