Laravel关系返回null

时间:2014-07-01 07:05:04

标签: php mysql laravel orm laravel-4

我想为使用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_id中的

user_profile.user_id1000

我想在控制器中使用此行访问用户个人资料:

public function getIndex()
{

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

dd()的结果是:

NULL

我的关系问题是什么?

4 个答案:

答案 0 :(得分:4)

看起来没有加载关系。

尝试使用eager-loading

加载它们
User::with('user_profile')->get();

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

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

由于您使用的是除id之外的其他主键属性,因此您需要指定它(或在您的关系声明中):

protected $primaryKey = 'user_id';

答案 1 :(得分:1)

对于您的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_id重命名为users.id,则所有内容都可以正常运行而不做任何更改。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

对我来说,正如@zwacky建议的那样,解决方案是急切的加载:

  

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

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

这将在刚刚创建user_profile时执行解决方案,您需要在代码的其他部分访问user_profile$user。 看起来laravel不会立即更新父模型。