繁体   English   中英

Laravel关系返回null

[英]Laravel relationship is returning null

我想创建简单的关系,以User模型在数据库中查找用户的个人资料信息。

在User.php中,我有:

class User extends Eloquent implements UserInterface, RemindableInterface {
    ...
    public function profile() {
        return $this->hasOne('UserProfile');
    }
    ...
}

并在model / UserProfile.php中:

class UserProfile extends Eloquent{

    protected $table='user_profile';
    public function user() {
        return $this->belongsTo('User');
    }
}

数据库中的users.user_iduser_profile.user_id1000

我想通过控制器中的此行访问用户个人资料:

public function getIndex()
{

    $profile = $user->profile;
    dd( $profile );
    die;
}

dd()结果是:

NULL

我的人际关系问题是什么?

好像没有加载关系。

要么尝试使用eager-loading加载它们

User::with('user_profile')->get();

或稍后通过延迟加载来加载它们:

$user = Auth::user();
$user->load('user_profile');

另外,由于您使用的是id以外的另一个主键属性,因此需要指定它(或在关系声明中):

protected $primaryKey = 'user_id';

对于您的users表,您使用的是与预期不同的id以外的其他主键,因此在您的User模型中,您应明确声明protected $primaryKey = 'user_id' ,并且您也可以使用以下方法:

// Not tested with same foreign and local key
return $this->hasOne('UserProfile', 'user_id', 'user_id');

但是最好将两个密钥保持不同,可能您可以将users.user_id重命名为users.id 如果重命名users.user_idusers.id那么一切都将不工作,在所有的任何更改。

我曾经遇到过同样的问题,原因是该列后面有一个空白,可以用作关系。 只需删除即可解决。 可能与您的问题没有直接关系,但是我相信这可以节省一些通过搜索引擎访问此页面的人。

对我来说,解决方案急于加载,就像@zwacky建议的那样:

或稍后通过延迟加载来加载它们:

>$user = Auth::user();
>$user->load('user_profile');

当刚刚创建了user_profile并且您需要在代码的另一部分中通过$user访问user_profile时,这将解决该问题。 看起来laravel不会立即更新父模型。

暂无
暂无

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

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