如何检索和显示 Laravel 中的 Eloquent 关系

How to retrieve and display Eloquent relationships in Laravel

我想要完成的事情:

检索与经过身份验证的用户相关的所有 App\Post 模型并将它们显示在视图中。


我收到的错误:

单击 <a name="posts"> 标签时

Undefined variable:Property [id] does not exist on this collection instance


我一直在尝试的:

页面控制器:

 public function show($id) {
    $user = User::find($id);
    return view('pages.index', compact('user'));
}

索引 :

@extends('layouts.app')

@section('content')
    <h1>Welcome to notesite!</h1>
    
        <a href="/notes/show/{{ Auth::user()->id }}" name="posts">Show your posts</a>

    
@endsection

路线 :

Route::get('/', function () {
    return view('welcome');
});
Route::get('/pages/index', 'PagesController@index');
Route::get('/pages/about', 'PagesController@about');
Route::get('/pages/services', 'PagesController@services');

Route::get('/notes/index', 'NotesController@index');
Route::get('/notes/show/{user}', 'NotesController@show');
Auth::routes();
    
Route::get('/home', 'HomeController@index')->name('home');

谁能提供解决方案?

欢迎来到 SO!

如果您打算处理大量记录,我建议您继续阅读 Eloquent relationships, especially the part about eager loading

您可以执行以下操作:

用户模型

// Add this bit to your existing model to define the relationship 
// ( assuming that 1 user can have many different posts )

public function posts() {
    return $this->hasMany('App\Post');
}

Post型号

// By default, Eloquent will automatically determine the proper foreign key column,
// noted here as user_id

protected $fillable = ['title', 'body', 'user_id'];

Post控制器

public function show() {
    $posts = App\User::find(Auth::id())->posts; // Fetch the authenticated users posts

    return view('show-posts', compact('posts') ); // Pass them back to the view
}

routes/web.php

Route::view('/pages/index', 'index');
Route::get('/posts/show', 'PostController@show');

index.blade.php

<a href="/posts/show">Show user-specific posts!</a>

show-posts.blade.php

@foreach( $posts as $post )
    {{ $post->body }}
@endforeach