ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-12 04:39:50  阅读:209  来源: 互联网

标签:php laravel laravel-5-2 laravel-5-1


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

帖子模型中的回复功能

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

帖子表

enter image description here

通过$post->查看我在哪里访问答复

<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,通过它我将关系链接到表本身.

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

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

更新:请注意,用户评论的所有回复都存储在具有唯一ID的数据库表帖子中,即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);

标签:php,laravel,laravel-5-2,laravel-5-1
来源: https://codeday.me/bug/20191012/1898059.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有