【发布时间】:2014-08-23 03:13:23
【问题描述】:
我的 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');
}
我确信表配置文件中的所有行都有一个 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?!');
}
}
有时我会收到消息“配置文件未设置!为什么?!”
那么,为什么?!
【问题讨论】:
-
我怀疑它“有时”会发生,而是“一直”发生,但只针对特定用户。试试
print('profile is not set for' . $user->id);并调查这些记录? -
我猜一个配置文件可能有多个用户。在这种情况下,不应该将关系声明为: $this->belongsTo('Profile'); ?
-
我忘记更新了...这是我的错:我找到了一个没有通讯用户的个人资料。
标签: laravel eloquent eager-loading