【问题标题】:Laravel Call to a member function first() on nullLaravel 在 null 上调用成员函数 first()
【发布时间】:2020-10-22 09:02:42
【问题描述】:

我正在使用 VueJS 和 Laravel 来开发我正在开发的应用程序。我试图在这里搜索答案,但我没有找到任何有效的方法。大多数时候,这是因为没有什么可以返回,但我尝试调试我的查询相当多,但我不明白为什么我总是得到一个空值。

所以我正在尝试获取有关已登录学生的信息,因此我正在执行以下操作的路线上执行 axios get:

public function getByUserId($id) {
    //$student = $this->studentRepo->findByUserId($id);
    $student = Student::where('user_id', $id)->first();
    $inscription = Inscription::where('student_id', $student->id)->first();
    $student->careers;

    $res = $inscription ? new InscriptionResource($inscription) : '';

    return response()->json([
        'student' => new StudentResource($student),
        'inscription' => $res,
    ]);
}

问题是,它找不到具有该 user_id 的学生。我已经检查了 user_id (param: $id) 是否按预期到达那里,并且确实如此。我还尝试通过 ->toSql() 获取查询并将查询复制粘贴到数据库上以对其进行测试,并且我确实得到了我正在尝试搜索的学生。问题是,由于某种原因,它在 Laravel 中没有找到它,我不确定为什么。

我的学生表确实有属性“user_id”,我已经检查过了。

学生档案:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Student extends Model {
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    public function charges() {
        return $this->hasMany('App\Models\Payment');
    }
}

【问题讨论】:

  • 语法似乎是正确的。您在哪一行收到错误?
  • @user8555937 在第三行 "$student = Student::where('user_id', $id)->first();"我不断收到“在 null 上调用成员函数 first()”。正如我所提到的,我手动执行了查询并且它可以工作,但不是在 Laravel 中。
  • 您确定 Student 是 Eloquent 模型吗?如果可以,请发布其代码
  • @user8555937 我用代码编辑了我的原始帖子,我没有创建那个文件,我对模型的了解非常有限,但它似乎是一个。奇怪的是,我在另一个函数上做了同样的查询,而且它应该可以正常工作。
  • 改用Student::select('*')-&gt;where('user_id', $id)-&gt;first();。你有什么 Laravel 版本?

标签: php sql laravel


【解决方案1】:

在关系函数中添加相关列

public function charges() {
        return $this->hasMany('App\Models\Payment', '');
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2017-12-04
    • 2016-09-04
    • 2016-06-29
    • 2018-04-03
    • 2021-10-06
    • 2019-06-17
    相关资源
    最近更新 更多