dongzhuji1042 2014-06-23 15:01
浏览 45

Laravel 4.0:急切加载错误 - 试图获取非对象的属性

I'm trying to utilize the eager loading feature in laravel but it doesn't work as i expected. When i try to check the profile of user who doesn't have information in Profiles table it throws "Trying to get property of non-object" instead of giving a NULL value. I have separated users information into two tables -> users table and Profiles table. How can i get past that?!

ProfilesController.php

    use Illuminate\Database\Eloquent\ModelNotFoundException;
    class ProfilesController extends \BaseController {

    public function show($username)
{
    try {
    $user = User::with('profile')->whereUsername($username)->firstOrFail();


    } catch (ModelNotFoundException $e) {

        return Redirect::home()->with('globalerror', 'The user you are trying to search does not exists!');

    }
    return View::make('profiles.show')->withUser($user);
}
   }

Profiles.php Model

    class Profile extends Eloquent
    {

        public function owner(){
         return $this->belongsTo('User', 'user_id');
          }
    }

Users.php model

    use Illuminate\Auth\UserInterface;
    use Illuminate\Auth\Reminders\RemindableInterface;

    class User extends Eloquent implements UserInterface, RemindableInterface {

protected $table = 'users';

    protected $fillable = array('first_name', 'last_name', 'username', 'email', 'password', 'password_temp', 'code', 'active');



    public function profile(){
    return $this->hasOne('Profile');
     }


   }
  • 写回答

3条回答 默认 最新

  • dongpobo6009 2014-06-23 15:13
    关注

    That is one downfall of using the with() function. It will return a user even if the user does not have a profile.

    What you can do is make sure there is a profile using something like isset($user->profile) ? $user->profile : 'user does not have a profile';

    Or you can use has() in place of with() which will only get the user if it has a profile.

    评论

报告相同问题?

悬赏问题

  • ¥15 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序