Laravel $ posts-> comments()不在这里工作

时间:2014-06-11 17:44:38

标签: php laravel laravel-4 eloquent

以下是我的模特的代码:

models/Book.php

  

class Book extends \ Eloquent {

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

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

public function cover()
{
    return $this->morphMany('Image', 'imageable');
}

public function delete()
{
   $this->posts()->comments()->delete();

    $this->posts()->delete();

    $this->cover()->delete();
    // delete the model
    return parent::delete();
}
     

}

models/Post.php

  

Class Post扩展了Eloquent {

function book() {
    return $this->belongsTo('Book');
}

function comments() {
    return $this->hasMany('Comment');
}

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

public function delete()
{
    $this->comments()->delete();
    // delete the model
    return parent::delete();
}
     

}

models/Comment.php

  

课堂评论扩展了Eloquent {

function post() {
    return $this->belongsTo('Post');
}

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

}

但是在UserController.php我无法访问我的评论。我试过这些代码:

public function show($id)
{
        $user = User::find($id);

        $posts = Post::whereUserId($user->id)
                  ->orderBy('created_at','deac')->get();

        $comments = $posts->comments();
        dd($comments);
}

这总是说: enter image description here

如何在帖子下查看我的评论?我也不认为$this->posts()->comments()->delete();不起作用。

1 个答案:

答案 0 :(得分:3)

User模型中添加如下关系:

// User model
public function books()
{
    return $this->hasMany('Book');
}

然后在controller

public function show($id)
{
    // User->hasMany:books->hasMany:posts->hasMany:Comments
    $user = User::with('books.posts.comments')->find($id);
    return View::make('viewName')->with('user', $user);
}

然后在view

{{ $user->nameMaybe }}
{{ $user->emailMaybe }}
@foreach($user->books as $book)
    {{ $book->title }}
    {{ $book->author }}
    @foreach($book->posts as $post)
        {{ $post->slugMaybe }}
        {{ $post->postTitleMaybe }}
        @foreach($post->comments as $comment)
            {{ $comment->commenttextMaybe }}
        @endforeach
    @endforeach
@endforeach

返回的User模型的结构将是这样的(根据您的关系):

Model: User (object)
           ->name (Property of User Model)
           ->email (Property of User Model) and more properties
           -> books (property of User Model, collection of Book Models
              -> [0] Book (has properties)
              -> [1] Book (has properties
                 -> posts (property of [1]Book, collection of Post Models
                 -> [0] Post (has properties)
                 -> [1] Post (has properties
                    -> comments (property of [1]Post, collection of Comment Models
                    -> [0] Comment (has properties)
                    -> [1] Comment (has properties