php - 无法检索数据 laravel4(oneToMany)

标签 php mysql database orm laravel

好吧,我刚刚开始学习 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/

相关文章:

javascript - 必须单击提交按钮两次才能提交表单 - Java 脚本修复不起作用

php - 将用户重定向到登录时特定于其帐户的页面

MySQL使用varchar列进行分表查询

python - Django南迁错误: Key is Not Present

java - 无法通过 fragment 内的上下文菜单从自定义 ListView 中删除数据库行 - Android

mysql - 创建一个新表,其中为另一个表中的每个元素创建一列

php - 在特定条件下重做最后一个 foreach 循环命令

c# - 您的 SQL 语法有错误,请检查与您的 MariaDB 服务器版本相对应的手册,以了解在“[Id]”附近使用的正确语法

mysql - 从辅助 Linux 服务器备份 SQL 数据库

php - 从另一个表回填表;不能有重复