laravel - 如何在 Laravel 中检索和显示 Eloquent 关系
问题描述
我要完成的工作:
检索App\Post
与经过身份验证的用户相关的所有模型并在视图中显示它们。
我收到的错误:
Undefined variable:
以及Property [id] does not exist on this collection instance
点击<a name="posts">
标签时。
我一直在尝试的:
页面控制器:
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 关系,特别是如果你打算处理大量记录,那么关于急切加载的部分。
您可以执行以下操作:
用户模型
// 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');
}
后模型
// By default, Eloquent will automatically determine the proper foreign key column,
// noted here as user_id
protected $fillable = ['title', 'body', 'user_id'];
后控制器
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
}
路线/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
推荐阅读
- linux - 使用 ffmpeg 将实时视频从树莓派流式传输到 Web 服务器以进行分发
- ruby - 数组中的整数要么完全奇数,要么完全偶数,除了一个整数
- c# - 如何在winform上绘制矩阵
- bash - 在 TSV 中第 n 次出现值后删除行
- reactjs - 如何升级到 react native 0.59?
- python - Keras 中 CNN 的丢失在训练的某个时刻变成了 nan
- javascript - JointJS 中的两个端口位置
- javascript - 使用 Razor 将控件动态添加到 HTML 表格
- excel - 如何检测单元格数组中的点击
- pcm - 尝试使用 AudioKit 将 PCM 转换为 MP3 时崩溃