【发布时间】:2017-08-30 11:08:04
【问题描述】:
这是我的 PostController 控制器:
public function getAllPosts() {
$posts = Posts::all();
/*foreach ($posts as $post){
/* $username = $post->user->name;
//do something with $username
}*/
return View::make('welcome', compact('posts'));
//here the $detailed_posts can be defined in the 'do something' above
}
这是我的用户模型 Eloquent
代码class User extends Eloquent {
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password',
];
public function posts(){
return $this->hasMany('App\Post');
}
后模型雄辩
class Posts extends Eloquent {
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
public function user(){
return $this->belongsTo('App\User','user_id');
}
这是我的welcome.blade.php
@foreach ($posts as $post)
<div class="col-sm-7">
<hr>
<h2>{{ $post->title}}</h2>
<h5>
<span class="glyphicon glyphicon-time"></span> Post by {{$post->user->username}}, Sep 27, 2015.
</h5>
@endforeach
{{$post->user->username}} 出现错误
我已经尝试过使用{{$post->user['username']}},但没有显示任何用户价值。
有人可以在这个过程中帮助我吗?
【问题讨论】:
-
错误声明非常清楚,正如您已经提到的 $post->user['username'] 有效。我假设这里 $post->user 返回一个数组而不是一个对象。看看你得到了什么 var_dump($post->user);
-
只需检查所有帖子是否有 user_id,如果至少有一个没有,您将收到此错误(假设关系有效)
-
不熟悉 eloquent 但仍然建议尝试更改 post 模型中的用户关系:代替 belongsTo - 尝试 hasOne
-
与 dd($posts)?
-
User_id 大写.....应该是 user_id,修复你的数据库