所以我在使用Laravel的急切加载检索信息时遇到了问题。 I.m尝试将所有Post对象与他们尊敬的用户添加到查询中。检索幼虫中帖子的用户信息的问题
以下是我有:
查询是
public function index()
{
$posts = Post::with('user')->get();
return view('posts.index', compact('posts', $posts));
}
在我的用户和帖子车型我都各有定义,我认为是适当的关系,在这里,他们是完全:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts() {
return $this->hasMany('App\Post');
}
}
和邮政是:
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'title', 'content', 'followers',
];
public function user() {
return $this->belongsTo('App\User');
}
}
我得到的错误就是没有关于用户,如他们的名字,这是我要显示所有帖子的时候在对文章索引页的循环利用信息后正在返回。
有什么我错过了吗?
邮政和用户甚至如何连接? – Neat