【问题标题】:Laravel whereNull and where clause returns empty objectLaravel whereNull 和 where 子句返回空对象
【发布时间】:2021-02-07 04:42:46
【问题描述】:

我是 laravel 的新手。我试图从我的数据库中获取一些“父”列是“空”的记录。但它总是返回 空对象。然后我使用 toSql() 函数获取查询并在数据库上手动运行它。查询工作正常。为什么 laravel 什么都不返回?

laravel 版本是:8.1.0

这是我的模型

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'child_level',
        'type',
        'meta_url',
        'meta',
        'parent'
   ];

    public function teacher() {
        return $this->belongsToMany(
           Teacher::class,
           'category_teachers',
           'category_id',
           'teacher_id',
         );
    }
}

这是我在控制器中的功能

public function mainCourses() {
    $main_courses = Category::whereNull('parent');
    if (isset($main_courses)) {
        return response(['main_courses' => $main_courses], 200);
    }
    return response(['message' => 'No main courses in database'] , 404);
}

这是数据库表

当我调用该方法时,它会返回这样的响应。

我想返回所有“父”列为“空”的记录。 这有什么问题?还有其他方法吗?帮帮我...

【问题讨论】:

  • 这就是NULL 应该做的,它不会显示任何东西。如果您需要显示NULL 字符串,请进行检查。如果是NULL,则显示字符串NULL
  • 不熟悉 Laravel,但 aren't you supposed 会做类似 $main_courses = DB::table('category')->whereNull('parent')->get(); 的事情。

标签: php mysql laravel eloquent


【解决方案1】:

$main_courses = Category::whereNull('parent');

$main_courses 在这种情况下将只是一个查询构建器

您应该使用 get() 函数从 DB 中获取结果

$main_courses = Category::whereNull('parent')->get();

【讨论】:

【解决方案2】:

试试这个:

$mainCourse = Category::whereNull('parent')->get();

if (!empty($mainCourse)) {
    return response(['main_courses' => $main_courses], 200);
 }

 return response(['message' => 'No main courses in database'] , 404);

【讨论】:

    猜你喜欢
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多