有很多返回空值的laravel

我对laravel的OnetoMany功能有疑问。我的目标是检索用户的不同代码: 代码型号:

 public function users(){
    return $this->belongsTo('App\Users');
}

用户模型:

    public function code(){
    return $this->hasMany('App\Code');
}

和我的控制器:

        $users= Users::find($id);
    dd($users->codes);

但是此函数返回“ null”。 我可以检索用户的数据,但不能检索关联的代码。 谢谢您帮忙 !

评论
  • 一南
    一南 回复

    您的代码中的几个问题:

    • $users = Users::find($id) returns a single record with the corresponding $id so naming it $users is a little misleading.
    • In your question your model class is defined as User but when calling it with find() you defined it as Users, don't know which one is right but all models names should be single, so User not Users.
    • in your User model the name of the function is code but you call it as users->codes that's wrong it should be users->code.
  • 之冰巧
    之冰巧 回复

    您应该将用户模型中的代码关系重命名为复数形式:

    public function codes()
    {
        return $this->hasMany('App\Code');
    }
    

    然后:

      $user= Users::with('codes')->find($id);
        dd($user->codes);
    

    请注意,find仅检索一个用户,因此将变量命名为'$ user'而不是'$ users'