[英]Laravel whereNull and where clause returns empty object
I'm new to laravel. I tried to fetch some records from my database which are "parent" column is "null".我是 laravel 的新手。我试图从我的数据库中获取一些记录,这些记录是“父”列为“空”。 But it returns always empty object. Then I got the query using toSql() function and ran it manually on database.但它总是返回空 object。然后我使用 toSql() function 获得查询并在数据库上手动运行它。 Query works fine.查询工作正常。 Why laravel returns nothing?为什么 laravel 什么都不返回?
laravel version is: 8.1.0 laravel 版本为:8.1.0
here is my model这是我的 model
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',
);
}
}
here is my function in controller这是我在 controller 中的 function
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);
}
this is the database table这是数据库表
when i call to the method it returns response like this.当我调用该方法时,它会返回这样的响应。
I want to return all the records with 'parent' column is 'null'.我想返回所有“parent”列为“null”的记录。 what is the wrong with this?这有什么问题? is there an other way to do this?还有其他方法吗? Help me...帮我...
$main_courses = Category::whereNull('parent'); $main_courses = Category::whereNull('parent');
$main_courses
in this case will be just a query builder $main_courses
在这种情况下将只是一个查询生成器
you should get the result from DB using get() function您应该使用 get() function 从数据库中获取结果
$main_courses = Category::whereNull('parent')->get();
Try this:试试这个:
$mainCourse = Category::whereNull('parent')->get();
if (!empty($mainCourse)) {
return response(['main_courses' => $main_courses], 200);
}
return response(['message' => 'No main courses in database'] , 404);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.