使用findOrFail

时间:2016-08-16 20:59:53

标签: php laravel eloquent

我试图在我的网站上获取与给定用户相关的个人资料。

关系设置正确(我可以执行此操作:Auth::user() -> profile来访问个人资料数据。但是当我尝试执行此操作时:User::findOrFail(1) -> profile它会给我一个错误,说明它不是一个对象(并且profile的值等于null。为什么会这样?是的,ID为1的用户确实存在。

在我的User模型中,我设置了这个:

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

在我的Profile模型中,我做到了这一点:

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

我抓住X用户并在foreach循环中浏览它们时才看到这个问题,如下所示。

    <div class="thumbs-wrapper text-center">

        @foreach ($last_online as $user)
            <div class="thumb @if(\App\User::isOnline($user -> id)) online @else offline @endif">
                <a href="/profile/view/{{ $user -> id }}">
                    <img src="{{ asset($user -> profile -> picture) }}">
                </a>
            </div>
        @endforeach

    </div>

可能有什么不对?提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,请尝试此操作

User::with('profile')->where('id', '=', 1)->firstOrFail();

或者如果您需要使用其个人资料加载许多用户

User::with('profile')->take(10)->get();

答案 1 :(得分:0)

Call to undefined method Illuminate\Database\Query\Builder::profile()

profile()存在于用户模型中?

嗯......它必须工作。

在用户模型中:

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

在您的控制器方法中:

$users =  User::with('profile')->get();


dd($users);
  

Illuminate \ Database \ Query \ Builder :: profile()这里也是截图:   i.imgur.com/zPJEaC5.png很奇怪我可以使用Auth :: user() - &gt;简档

:)

foreach ($users as $user) {
 $user->profile->user_id; //(or whathewer)
}