【问题标题】:Laravel - Eager loaded object is not setLaravel - 未设置急切加载的对象
【发布时间】: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


【解决方案1】:

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

// 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();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 2021-04-23
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 2021-12-01
    • 2016-02-09
    相关资源
    最近更新 更多