使用hasMany关系时如何从帖子表中获取用户

编程入门 行业动态 更新时间:2024-10-19 15:39:11
本文介绍了使用hasMany关系时如何从帖子表中获取用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对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关系时如何从帖子表中获取用户

本文发布于:2023-10-24 20:16:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   帖子   用户   hasMany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!