无法检索数据laravel4(oneToMany)

时间:2014-05-22 21:48:57

标签: php mysql database orm laravel

好的,所以我刚刚开始学习Laravel,它非常棒。我只是试图从用户那里检索所有帖子。这是我的代码

模型/ user.php的

public function posts()
{
    $this->hasMany('Post');
}

模型/ post.php中

public function user()
{
    $this->belongsTo('User');
}

控制器/ UserController.php

public function getUserProfile($username)
{
    $user = User::where('username', '=', $username)->first();
    $this->layout->content = View::make('user.index', array('user'=>$user));
}

视图/用户/ index.blade.php

<div class="show-post">
        <ul>
            <li>{{ $user->posts }}</lo>
        </ul>
    </div>

我也尝试过:

@foreach($user->posts as $post)
     <li>{{$post->post}}</li>
@endforeach

因此我无法显示每个特定用户的帖子。谢谢。

2 个答案:

答案 0 :(得分:1)

所以在@ WereWolf-The Alpha的帮助下,我能够解决它并使我的代码更好,如果你注意到我忘了返回我的关系函数。例如:

注意我没有在

之前退回

模型/ post.php中

public function users()
{
     return $this->belongsTo('users');
}

但是我查询数据库的方式效率也很低,因此Alpha向我展示了Eager Loading http://laravel.com/docs/eloquent#eager-loading

控制器的例子

public function getUserProfile($username)
{
    $user = User::with('posts')->where('username', '=', $username)->first();
    $this->layout->content = View::make('user.index', array('user'=>$user));
}

最后是观点:

div class="show-post">
        @foreach($user->posts as $post)
            {{ $post->post }}
        @endforeach
</div>

答案 1 :(得分:0)

实际上$user->posts会返回Post模型的集合,因此当您尝试此

{{ $user->posts }}

Laravel尝试回显那个不可能的集合对象。您可以尝试foreach循环:

@foreach($user->posts as $post)
    {{ $post->somepropertyname }}
@endforeach

也可以这样做:

// Get first post->somepropertyname
{{ $user->posts->first()->somepropertyname }}

// Get last post->somepropertyname
{{ $user->posts->last()->somepropertyname }}

// Get first post->somepropertyname (same as first)
{{ $user->posts->get(0)->somepropertyname }}

// Get second post->somepropertyname from collection
{{ $user->posts->get(1)->somepropertyname }}

// Get the post->somepropertyname by id (post id) 2
{{ $user->posts->find(2)->somepropertyname }}

你也可以像这样(更好)使用渴望加载:

$user = User::with('posts')->where('username', '=', $username)->first();

您可能希望this article关于Cocllection

更新:在模型方法中也使用return,例如:

public function posts()
{
    return $this->hasMany('Post');
}