【问题标题】:Call to a member function empresas() on null - Laravel在 null 上调用成员函数 empresas() - Laravel
【发布时间】:2019-06-17 11:12:09
【问题描述】:

我有两个模型:Empresa 和 Postulante。这种关系是多对多的。

Empresa 模型

public function postulantes()
{
    return $this->belongsToMany(Postulante::class);
}

后置模型

public function empresas()
{
    return $this->belongsToMany(Empresa::class)->where('empresa_postulante.activo', 1)->orderBy('empresa_postulante.created_at');
}

PostulanteController(为一个 Postulante 获取 Empresas)

public function index()
{
    $usuario_actual = \Auth::user(); //obtengo los datos del usuario en sesion
    $usuario_id = $usuario_actual->id;
    $postulante = Postulante::where('pos_usuario', $usuario_id)->first();
    $empresas = $postulante->empresas();

    return view('postulantes/dash-postulante', compact('empresas'));
}

由于关系表(empresa_postulante)中没有数据,我收到以下错误消息:

在 null 上调用成员函数 empresas()

【问题讨论】:

  • $postulante 是一个空值。您的 first() 方法可能没有返回任何结果。在调用 empresas() 之前检查 $postulante 的数据

标签: php laravel laravel-5 eloquent


【解决方案1】:

看起来像:

$postulante = Postulante::where('pos_usuario', $usuario_id)->first();

...没有返回任何结果。

【讨论】:

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