Laravel Associate 方法在视图中返回空数组

Laravel Associate method is returning empty array in the view

我正在开发一个简单的社交网络,现在正在处理回复部分。我将 post/status 模型与用户相关联,如下所示,但是当我尝试在视图中访问它时 return 是空数组 [].

Post模型中的回复功能

public function postReply(Request $request, $statusId){
        $this->validate($request, [
            "reply-{$statusId}" => 'required|max:1000',
        ],
        [
            'required' => 'The reply body is required'
        ]
        );

        $post = Post::notReply()->find($statusId);
        if(!$post){
            return redirect('/');
        }

        if(!Auth::user()->isFriendsWith($post->user) && Auth::user()->id !== $post->user->id){
            return redirect('/');
        }

        $post = Post::create([
            'body' => $request->input("reply-{$statusId}"),
        ]);
        $post->user()->associate(Auth::user());
        $post->replies()->save($post);


        return redirect()->back();
    }

Post型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';
    protected $fillable = ['body'];
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function likes(){
        return $this->hasMany('App\Like');
    }

    public function scopeNotReply($query){
        return $query->whereNull('parent_id');
    }

    public function replies(){
        return $this->hasMany('App\Post', 'parent_id');
    }
}

Posts Table

查看我通过 $post->replies

访问回复的位置
<section class="row new-post">
        <div class="col-md-6 col-md-offset-3">
            <header><h3>What do you have to say?</h3></header>
            <form action="{{ url('createpost') }}" method="post">
                <div class="form-group">
                    <textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your Post"></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Create Post</button>
                <input type="hidden" value="{{ Session::token() }}" name="_token">
            </form>
        </div>
    </section>
    <section class="row posts">
        <div class="col-md-6 col-md-offset-3">
            <header><h3>What other people say...</h3></header>
                @foreach($posts as $post)
                <article class="post media" data-postid="{{ $post->id }}">
                    <a class="pull-left" href="{{ url('user', $post->user->username) }}">
                        <img class="media-object" alt="" src="{{ $post->user->getAvatarUrl() }}">
                    </a>
                    <div class="media-body">
                      <h4 class="media-heading"><a href="{{ url('user', $post->user->username) }}"> {{ $post->user->username }}</a></h4>
                        <p>{{ $post->body }}</p>
                        <ul class="list-inline">
                            <li>{{ $post->created_at->diffForHumans() }}</li>
                            <li><a href="#">Like</a></li>
                            <li>10 likes</li>
                        </ul>
                        {{ $post->replies }}

                    </div>

                    <form role="form" action="{{ url('createpost',  $post->id )}}" method="post">
                            <div class="form-group{{ $errors->has("reply-{$post->id}") ? ' has-error': '' }}">
                                <textarea name="reply-{{ $post->id }}" class="form-control" rows="2" placeholder="Reply to this status"></textarea>
                                @if($errors->has("reply-{$post->id}"))
                                    <span class="help-block">{{ $errors->first("reply-{$post->id}") }} </span>
                                @endif
                            </div>
                            <input type="submit" value="Reply" class="btn btn-default btn-sm">
                            <input type="hidden" name="_token" value="{{ Session::token() }}">
                    </form>

                </article>

                @endforeach

        </div>

</section>

PS :我正在使用一个 table 作为关系,即 posts 并且在 posts table 中有一个列名 parent_id 通过它我将关系与 table 自身联系起来。

{{ $post->replies }} returns 空数组。按照逻辑,它应该 return 与回复相关的评论回复。

如果还需要什么,就说我会分享。

更新: 请注意,用户评论的所有回复都存储在数据库中 table posts 具有唯一 ID,即 parent_id 唯一的问题是,当我尝试访问它时,它 return 是空数组。

您正在为父 post 和回复使用 $post,因此在

$post->replies()->save($post);

你实际上是在将 $post 设置为对自身的回复。

还值得注意的是,列 id 是未签名的,但 user_idparent_id 不是。我猜这些上面设置了外键?

编辑

尝试使用新的 $reply 变量。

public function postReply(Request $request, $statusId){
    $this->validate($request, [
        "reply-{$statusId}" => 'required|max:1000',
    ],
    [
        'required' => 'The reply body is required'
    ]
    );

    $post = Post::notReply()->find($statusId);
    if(!$post){
        return redirect('/');
    }

    if(!Auth::user()->isFriendsWith($post->user) && Auth::user()->id !== $post->user->id){
        return redirect('/');
    }

    $reply = Post::create([
        'body' => $request->input("reply-{$statusId}"),
    ]);
    $reply->user()->associate(Auth::user());
    $post->replies()->save($reply);


    return redirect()->back();
}

你的关系设置错了。在您的 post 模型中,而不是 post 具有自身的一对多关系。应该是这样的:

// App\User.php
public function replies()
{
    return $this->hasMany(App\Reply::class);
}

// App\Post.php
public function replies()
{
    return $this->hasMany(App\Reply::class);
}

// App\Reply.php
public function post()
{
    return $this->belongsTo(App\Post::class);
}

public function user()
{
    return $this->belongsTo(App\User::class);
}

public function comments()
{
    return $this->belongsTo(App\Reply::class, 'parent_id');
}

您似乎在将 $post 变量传递给您的视图时没有附加回复。
我们必须使用 with() 方法来连接这两个表。
试一下,如下:

if(Auth::check()){ 
            $posts = Post::notReply()
                    ->where(function($query){ 
                        return $query->where('user_id', Auth::user()->id)
                                ->orWhereIn('user_id', Auth::user()->friends()->lists('id'));
                    })
                    ->with('replies')//Here we are joining the replies to the post
                    ->orderBy('created_at', 'desc')
                    ->get();
                    return view('timeline.index', compact('posts')); 
                }

现在,在您的视图中,您需要使用 2 个 foreach 循环,如下所示:

@foreach($posts as $post)
    {{--Your Code --}}
    @foreach($post->replies as $reply)
        {{--Your Code --}}
    @endforeach
    {{--Your Code --}}
@endforeach

更新:

postReply() 方法有问题。在旧代码中,您覆盖了 $post 变量,因此回复将 parent_id 作为它自己的 id.
因此,使用 $reply 变量替换旧代码。
旧:

$post= Post::create([
   'body' => $request->input("reply-{$statusId}"),
]);
$post->user()->associate(Auth::user());
$post->replies()->save($post);

新:

$reply = Post::create([
   'body' => $request->input("reply-{$statusId}"),
]);
$post->user()->associate(Auth::user());
$post->replies()->save($reply);