【发布时间】: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