简体   繁体   English

有很多返回 null 值 laravel

[英]Has many return null value laravel

I'm having a problem with laravel's OnetoMany feature.我对 laravel 的 OnetoMany 功能有疑问。 My goal is to retrieve the different codes of a user: Code Model:我的目标是检索用户的不同代码:代码 Model:

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

User model:用户 model:

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

And my controller:还有我的 controller:

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

But this function is returning "null".但是这个 function 返回“null”。 I can retrieve my user's data but not the associated codes.我可以检索我的用户数据,但不能检索相关代码。 Thank for your help !感谢您的帮助 !

Couple of issues in your code:您的代码中有几个问题:

  • $users = Users::find($id) returns a single record with the corresponding $id so naming it $users is a little misleading. $users = Users::find($id)返回带有相应$id单个记录,因此将其命名为$users有点误导。
  • 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 .在您的问题中,您的 model class 被定义为User但是当使用find()调用它时,您将其定义为Users ,不知道哪个是正确的,但所有型号名称都应该是single ,所以User不是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 .在您的用户model 中,function 的名称是code()但您将其称为$users->codes是错误的,它应该是$users->code

you should rename the code relation in user model to be plural:您应该将用户 model 中的代码关系重命名为复数:

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

and then:接着:

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

please note that find retrieve only one user so name the variable '$user' not '$users'请注意,find 只检索一个用户,因此将变量命名为“$user”而不是“$users”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM