好吧,我刚刚开始学习 Laravel,它很棒。我只是在尝试检索用户的所有帖子时遇到了困难。这是我的代码
模型/User.php
public function posts()
{
$this->hasMany('Post');
}
模型/Post.php
public function user()
{
$this->belongsTo('User');
}
Controller /UserController.php
public function getUserProfile($username)
{
$user = User::where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
View /用户/index.blade.php
<div class="show-post">
<ul>
<li>{{ $user->posts }}</lo>
</ul>
</div>
我也试过:
@foreach($user->posts as $post)
<li>{{$post->post}}</li>
@endforeach
所以我无法为每个特定用户显示帖子。谢谢。
最佳答案
因此,在@WereWolf- The Alpha 的帮助下,我能够解决它并改进我的代码,如果您注意到我忘记返回我的关系函数。示例:
注意我之前没有返回
模型/Post.php
public function users()
{
return $this->belongsTo('users');
}
但我查询数据库的方式也很低效,所以 Alpha 向我展示了 Eager Loading http://laravel.com/docs/eloquent#eager-loading
Controller 示例
public function getUserProfile($username)
{
$user = User::with('posts')->where('username', '=', $username)->first();
$this->layout->content = View::make('user.index', array('user'=>$user));
}
最后是 View :
div class="show-post">
@foreach($user->posts as $post)
{{ $post->post }}
@endforeach
</div>
关于php - 无法检索数据 laravel4(oneToMany),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23817636/