【问题标题】:Get arrays with null values, Laravel获取具有空值的数组,Laravel
【发布时间】:2020-09-14 02:11:57
【问题描述】:

我有一个查询,我尝试在某些条件下获取一些值,问题是最后我得到一个数组列表(例如 4),但字段值为空。不知道为什么..如果不满足某些条件,我希望什么也得不到,而不是一个空值的数组。

$questions = MyModel::select(
        'answer_statistics.id',
        'answer_statistics.paragraph_id',
        'paragraphs.free_text as free_text',
        'paragraphs.id as paragraph_id',
        'questions.best_match as best_match'
        )
        ->whereNotNull('answer_statistics.paragraph_id')
        ->leftJoin('paragraphs', 'answer_statistics.paragraph_id', 'paragraphs.id')
        ->leftJoin('questions', 'paragraphs.question_id', 'questions.id');

    if($excepted_questions){
        $questions->whereNotIn('answer_statistics.id', $excepted_questions);
    }

    if($confidence_specs->best_match){
        $questions->whereNotNull('questions.best_match');
    }

    if($confidence_specs->votes != 0 && $confidence_specs->weight != 0){
        $questions->where('answer_statistics.votes', '<=' , $confidence_specs->votes)
        ->orWhere('answer_statistics.weight', '<=' , $confidence_specs->weight);
    }

    $questions->inRandomOrder()
        ->limit(4)
        ->get();

    dd($questions->get());  // here I get 4 arrays with null values..

【问题讨论】:

  • 请详细说明。什么是错误/问题?你想达到什么目的?你期待的是什么?
  • 如果我没有行,那么我的 $questions 将为空。现在在我的 $questions 中,我有一个包含空值的数组列表,女巫不行。

标签: laravel laravel-7


【解决方案1】:

要从数组中删除空值,可以使用filter()

$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2020-09-12
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多