为什么我会尝试获取 属性 'username' of non-object 而 "owner_user" 中有信息?
Why do I get Trying to get property 'username' of non-object while "owner_user" has information in it?
HTML代码
@foreach($posts as $post)
<div class="container card mt-2" style="width: 32rem;">
<img src="{{ asset('images')."/".$post->img_url }}" class="card-img-top" alt="img not found">
<div class="card-body">
<h5 class="card-title">{{ $post->champion }} </h5>
<p class="card-text">{{ $post->owner_user->username }}</p>
</div>
</div>
@endforeach
Laravel代码
public function testpage()
{
return Posts::with(['OwnerUser','like'])->get();
}
当我只是 return 发布 table 时,它有包含用户信息的列 owner_user。
关系有效,但是当我在 HTML 代码中 return 时,我在 {{ $post->owner_user->username }} 中得到“Null”。
因为那不是一个单一的对象尝试
@foreach($posts as $post)
<div class="container card mt-2" style="width: 32rem;">
<img src="{{ asset('images')."/".$post->img_url }}" class="card-img-top" alt="img not found">
<div class="card-body">
<h5 class="card-title">{{ $post->champion }} </h5>
<p class="card-text">@(foreach $post->owner_user as $user){{$user->username }}@endforeach</p>
</div>
</div>
@endforeach
HTML代码
@foreach($posts as $post)
<div class="container card mt-2" style="width: 32rem;">
<img src="{{ asset('images')."/".$post->img_url }}" class="card-img-top" alt="img not found">
<div class="card-body">
<h5 class="card-title">{{ $post->champion }} </h5>
<p class="card-text">{{ $post->owner_user->username }}</p>
</div>
</div>
@endforeach
Laravel代码
public function testpage()
{
return Posts::with(['OwnerUser','like'])->get();
}
当我只是 return 发布 table 时,它有包含用户信息的列 owner_user。 关系有效,但是当我在 HTML 代码中 return 时,我在 {{ $post->owner_user->username }} 中得到“Null”。
因为那不是一个单一的对象尝试
@foreach($posts as $post)
<div class="container card mt-2" style="width: 32rem;">
<img src="{{ asset('images')."/".$post->img_url }}" class="card-img-top" alt="img not found">
<div class="card-body">
<h5 class="card-title">{{ $post->champion }} </h5>
<p class="card-text">@(foreach $post->owner_user as $user){{$user->username }}@endforeach</p>
</div>
</div>
@endforeach