PHP Laravel雄辩的关系在使用findOrFail时不起作用
我试图获取与我的网站上给定用户相关的配置文件。PHP Laravel雄辩的关系在使用findOrFail时不起作用
的关系是建立正确的(我可以这样做:Auth::user() -> profile
访问配置文件数据,但是当我尝试这样做:User::findOrFail(1) -> profile
它给了我一个错误说,它不是一个对象(和配置文件的值等于。null
这是为什么是的与1
的ID的用户确实存在
在我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>
什么可能是错的?提前致谢。
试试这个,如果我理解你的问题正确
User::with('profile')->where('id', '=', 1)->firstOrFail();
,或者如果你需要加载很多用户与他们的个人资料
User::with('profile')->take(10)->get();
这也不起作用。所有的用户都有个人资料。它是在用户注册时创建的,具有与用户相同的user_id。 这给了我这个错误:'调用undefined方法照亮\数据库\查询\生成器::配置文件()' – Kaizokupuffball
Call to undefined method Illuminate\Database\Query\Builder::profile()
轮廓()存在于用户模式?
嗯......它必须工作。
在用户模式:
public function profile() {
return $this->hasOne('App\Profile', 'user_id');
}
在你的控制器的方法:
$users = User::with('profile')->get();
dd($users);
Illuminate\Database\Query\Builder::profile() Here's a screenshot also: i.imgur.com/zPJEaC5.png So weird I can use Auth::user() -> profile
:)
foreach ($users as $user) {
$user->profile->user_id; //(or whathewer)
}
一个或多个在用户的foreach不具备个人资料,这就是全部 –
所有用户都有个人资料。它是在用户注册时创建的,具有与用户相同的user_id。我也在我的数据库管理器中手动检查了这个。 – Kaizokupuffball
然后检查堆栈跟踪并确定发生错误的位置。 –