0

Something strange is happening with my laravel 4.0 application. I have the table users and the table profiles. In their models:

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

// app/models/Profile.php:
public function user(){
    return $this->belongsTo('User');
}

I am sure all the rows in the table profiles has an user_id and it has a correspondent user in the table users, and vice versa. But when I do this:

$users = User::with('profile')->get();
foreach($users as $user){
    if(isset($user->profile)){
        print($user->profile->name);
    }
    else{
        print('profile is not set! why?!');
    }
}

Sometimes I get the message "profile is not set! Why?!"

So, why?!

cawecoy
  • 2,359
  • 4
  • 27
  • 36
  • I doubt that it happens "sometimes" but rather happens "all the time" but to specific users. Try `print('profile is not set for' . $user->id);` and investigate those records? – Unnawut Jul 02 '14 at 11:46
  • 1
    I guess a profile may have more than one user. In that case, shouldn't the relationship be declared as : $this->belongsTo('Profile'); ? – Javi Stolz Jul 02 '14 at 17:47
  • I forgot to update this... It was my fault: I found an profile without a correspondent user. – cawecoy Sep 02 '14 at 20:28

1 Answers1

1

There could be other reasons as well. IF you are sure that the corresponding User has a related Profile then make sure those profiles are not deleted. It often happens with soft deleted models. If you are using soft deleting then it could be a problem too. To find out you may try these:

// Get the users who has related Profile
$users = User::has('profile')->with('profile')->get();

Also try this:

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

Compare both results. This is just a guess.

The Alpha
  • 143,660
  • 29
  • 287
  • 307