Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel关系正在返回null_Php_Mysql_Laravel_Orm_Laravel 4 - Fatal编程技术网

Php Laravel关系正在返回null

Php Laravel关系正在返回null,php,mysql,laravel,orm,laravel-4,Php,Mysql,Laravel,Orm,Laravel 4,我想用usermodel创建简单的关系,以便在数据库中查找用户的配置文件信息 在User.php中,我有: class User extends Eloquent implements UserInterface, RemindableInterface { ... public function profile() { return $this->hasOne('UserProfile'); } ... } 在model/UserProf

我想用
user
model创建简单的关系,以便在数据库中查找用户的配置文件信息

在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\u id
user\u profile.user\u id
1000

我想使用控制器中的此行访问用户配置文件:

public function getIndex()
{

    $profile = $user->profile;
    dd( $profile );
    die;
}
dd()
的结果是:

NULL

我的关系有什么问题?

看起来关系没有加载

或者尝试使用

或者稍后使用延迟加载来加载它们:

$user = Auth::user();
$user->load('user_profile');
另外,由于您使用的主键属性不是
id
,因此需要指定它(或在关系声明中):


对于
用户
表,您使用的主键与
id
不同,因此在
用户
模型中,您应该明确声明
受保护的$primaryKey='User\u id'
,您也可以使用此项:

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

但是最好保持两个键不同,可能您可以将
users.id
重命名为
users.id
。如果您将
users.user\id
重命名为
users.id
,则一切都将正常工作,不会发生任何更改。

我也遇到过同样的问题,原因是列后面有一个空格,用作关系。简单地删除它就可以解决问题。可能与您的问题没有直接关系,但我相信这可能会为通过搜索引擎访问此页面的用户节省一些时间。

对我来说,解决方案是立即加载,正如@zwacky所建议的:

或者稍后使用延迟加载来加载它们:

$user = Auth::user();
$user->load('user_profile');
当刚刚创建了
user\u profile
并且您需要通过代码另一部分中的
$user
访问
user\u profile
时,这将实现解决方案。
看起来laravel没有立即更新父模型。

数据库中是否存在用户配置文件行?您的
getIndex()
从哪里获取其
$user
,从ProfileController中的@Unnawut访问用户配置文件,我假设
var\u dump($user->user\u id)
正在为您提供正确的用户id?您是否尝试过在您的
配置文件()中使用
$this->hasOne('UserProfile','user\u id','user\u id')
?我认为快速加载与此无关。但是,设置主键应该是一件令人沮丧的事情。。拉威尔还不够成熟
// Not tested with same foreign and local key
return $this->hasOne('UserProfile', 'user_id', 'user_id');
>$user = Auth::user();
>$user->load('user_profile');