Laravel Associate方法在视图中返回空数组 [英] Laravel Associate method is returning empty array in the view

查看:101
本文介绍了Laravel Associate方法在视图中返回空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个简单的社交网络上工作,现在正在答复部分中工作.我将发布/状态模型与用户关联如下,但是当我尝试在视图中访问时,它返回空数组[].

I am working on a simple social network, i am working on the replies section now. I associated the post/status model with user as below, but when i tried to access in the view it returns empty array [].

帖子模型中的回复功能

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();
    }

发布模型

<?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');
    }
}

帖子表

查看我通过$ 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:我正在使用一个表来建立关系,即职位,并且在职位表中有一个列名parent_id,通过它我将关系与表本身链接起来.

PS : I am using one table for the relationship i.e posts and in posts table there is a column name parent_id via which i am linking the relationship to the table with itself.

{{ $post->replies }}返回空数组.按照逻辑,它应该返回与回复有关的评论回复.

{{ $post->replies }} returns empty array. By logic it should return the replies of comment related to the replies .

如果还有其他需要,请提一下我会分享.

If any thing else is needed, just mention i will share.

更新:请注意,用户注释的所有回复都存储在具有唯一ID的数据库表帖子中,即parent_id唯一的是,当我尝试访问它时,它将返回空数组

UPDATE : Note that the all the replies the user comment is stored in the database table posts with unique id i.e parent_id The only thing is that when i try to access it it returns empty array.

推荐答案

在将变量传递到视图时,您似乎没有将答复附加到$post变量中.
我们必须使用with()连接这两个表的方法.
请尝试以下操作:

It seems like your are not attaching the replies to your $post variable while passing it to your view.
We have to use with() method to join these two tables.
Try, the following :

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循环,如下所示:

Now, in your View you would need to use 2 foreach loop like below:

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

更新:

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

Update:

Problem is with the postReply() method. In old code you were overriding the $post variable, due to which the reply was getting parent_id as its own id.
So, replace your old code with using $reply variable.
old:

$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);

这篇关于Laravel Associate方法在视图中返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆