gpt4 book ai didi

php - Laravel 关系返回 null

转载 作者:行者123 更新时间:2023-11-29 01:28:55 25 4
gpt4 key购买 nike

我想创建简单的关系,以便使用 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_id 中是 1000

我想在 Controller 中使用这一行访问用户配置文件:

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';

关于php - Laravel 关系返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24504297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com