How to get a user from post table when using hasMany relationship

前提是你 提交于 2021-01-28 12:13:13

问题


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 

My posts table looks like this:

id
user_id
title
content
created_at
updated_at


回答1:


You're not returning the user in the relation in your Post model, try this:

public function user(){

   return $this->belongsTo('App\User');
}

The name of the function should be user, on singular as @Ross Wilson suggested.

In your view you could do this:

@section('content')
    @foreach ($post as $p)
    {{$p->user->name }}
    @endforeach
@endsection



回答2:


You were close.

{{ $p->users->name }}

If you don't want to add clauses to your relationships then you can access it by treating it as a property.

I would suggest renaming your users() method to user() as a belongsTo relationship with will only ever return a single model. If you do that then you'll need to change the code in your blade file to $p->user->name.




回答3:


try
Blade view

@foreach ($post as $p)

{{$p->user->name }}

@endforeach

Controller

  public function main_page(){

    $post= Post::with('user')->latest()->get();


    return view('main' , compact('post') );
}

Model post

  public function user(){

    $this->belongsTo('App\User');
}


来源:https://stackoverflow.com/questions/55319161/how-to-get-a-user-from-post-table-when-using-hasmany-relationship

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!