使用hasMany关系时如何从帖子表中获取用户 [英] How to get a user from post table when using hasMany relationship
问题描述
我对Laravel还是很陌生,现在已经困扰了我好一段时间了,在尝试使用hasMany关系通过帖子表获取用户名时,我遇到了一个问题.希望添加的代码有助于更好地理解问题.谢谢
I am pretty new to Laravel and i have been stuck with this problem for quite a while now ,I face a problem when trying to get a user name through post table using hasMany relationship. Hope the added code helps to understand the problem better. Thank you
public function main_page(){
$post= Post::all();
return view('main' , compact('post') );
}
@extends('layouts.app')
@section('content')
@foreach ($post as $p)
{{$p->users()->name }}
@endforeach
@endsection
public function users(){
$this->belongsTo('App\User');
}
我希望显示该帖子的作者姓名,但实际情况并非如此.我收到错误消息:
I expect that author's name of the post would be displayed ,but it is not the case. I get an error:
Trying to get property 'name' of non-object
我的帖子表如下:
id
user_id
title
content
created_at
updated_at
推荐答案
您没有在您的 Post 模型中以关系返回用户,请尝试以下操作:
You're not returning the user in the relation in your Post model, try this:
public function user(){
return $this->belongsTo('App\User');
}
函数的名称应为 user
,如@Ross Wilson所建议的单数形式.
The name of the function should be user
, on singular as @Ross Wilson suggested.
您认为您可以这样做:
@section('content')
@foreach ($post as $p)
{{$p->user->name }}
@endforeach
@endsection
这篇关于使用hasMany关系时如何从帖子表中获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!