Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.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
Laravel-未设置已加载的对象_Laravel_Eloquent_Eager Loading - Fatal编程技术网

Laravel-未设置已加载的对象

Laravel-未设置已加载的对象,laravel,eloquent,eager-loading,Laravel,Eloquent,Eager Loading,我的laravel 4.0应用程序出现了一些奇怪的情况。我有表用户和表配置文件。在他们的模型中: // app/models/User.php: public function profile(){ return $this->hasOne('Profile', 'user_id'); } // app/models/Profile.php: public function user(){ return $this->belongsTo('User'); } 我确

我的laravel 4.0应用程序出现了一些奇怪的情况。我有表用户和表配置文件。在他们的模型中:

// app/models/User.php:
public function profile(){
    return $this->hasOne('Profile', 'user_id');
}

// app/models/Profile.php:
public function user(){
    return $this->belongsTo('User');
}
我确信表profiles中的所有行都有一个user_id,表users中有一个对应的用户,反之亦然。但当我这么做的时候:

$users = User::with('profile')->get();
foreach($users as $user){
    if(isset($user->profile)){
        print($user->profile->name);
    }
    else{
        print('profile is not set! why?!');
    }
}
有时我会收到这样的信息:“个人资料未设置!为什么?!”


那么,为什么

可能还有其他原因。如果您确定相应的
用户
具有相关的
配置文件
,请确保这些配置文件未被删除。这种情况经常发生在软删除模型上。如果您使用的是软删除,那么这也可能是一个问题。要找到答案,您可以尝试以下方法:

// Get the users who has related Profile
$users = User::has('profile')->with('profile')->get();
还可以尝试以下方法:

// Get users with profile even soft deleted ones
$users = User::with(array('profile' => function($query) {
    $query->withTrashed();
}))->get();

比较两个结果。这只是一个猜测。

我怀疑这种情况“有时”会发生,而“一直”会发生,只是针对特定的用户。尝试
print('配置文件未为'.$user->id'设置)并调查这些记录?我猜一个配置文件可能有多个用户。在这种情况下,关系不应该声明为:$this->belongsTo('Profile')?我忘了更新这个。。。这是我的错:我发现一个没有相应用户的个人资料。