我想显示评论所有者的用户名,但是评论表仅具有user_id

时间:2018-09-09 08:51:00

标签: php laravel

将包含注释的变量发送到视图后,我只能显示用户ID。这就是为什么我需要以某种方式遍历所有注释,并根据它们的user_id来添加具有username-username的新密钥对值,然后将其发送到视图。不幸的是,我在弄清楚该怎么做时遇到麻烦。

public function specificImage($id){
    $similarImages = null;
    $image = Image::with('comments.user')->find($id);
    $subImages = Image::where('parent_id', $id)->get();
    $views = $image->views;
    $image->views = $views + 1;
    $image->save();
    $authorId = $image->user_id;
    $author = User::find($authorId);
    $comments = Comment::where('image_id', $id)->get();
    $recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();

    $tag = Tag::whereHas('images', function($q) use ($id) {
        return $q->where('taggable_id', $id);
    })->first();

    if (!empty($tag)) {
        $tagId = $tag->id;
    }

    if (!empty($tagId)) {
        $similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
            return $q->where('tag_id', $tagId);
        })->orderBy('created_at', 'desc')->limit(9)->get();
    }

    return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}

表格:

Table: Comments
Columns: id, user_id, image_id, comment

图片模型:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function tags(){
        return $this->morphToMany('App\Tag', 'taggable');
    }

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

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

    public function updateVotes()
    {
        $this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
        $this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
        $this->save();
    }

    public function updateComments()
    {
        $this->comments = Comment::where('image_id', $this->id)->count();
        $this->save();
    }

}

评论模型:

   <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function image(){
        return $this->belongsTo('App\Image');
    }

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

}

用户模型:

   <?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

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

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

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

    public function roles(){
        return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
    }

    public function hasAnyRole($roles) {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                if ($this->hasRole($role)){
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles)){
                return true;
            }
        }
        return false;
    }

    public function hasRole($role){
        if ($this->roles()->where('name', $role)->first()){
            return true;
        }
        return false;
    }


}

刀片

@extends('layouts.app')
@section('content')

    <div class="specific-image-flexbox">

        <div class="specific-image-column">
            <div class='specific-image-container'>
                <img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
                @foreach($subImages as $subImage)
                    <img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
                @endforeach
            </div>
        </div>

        <div class="artwork-info-column">
            <div class="artwork-info-container">
                <p class='title'>{{ $image->name }}<p>
                <p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
                @if(Auth::user())
                    @if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
                        <a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
                    @endif
                @endif
                <p class='description'>{{ $image->description }}</p>
                <p class='description'>Техника: {{ $image->medium }}</p>
                <p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
                <p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
                <p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
                <a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
                <!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->

                <div class='social-container'>
                    <div class="addthis_inline_share_toolbox"
                        data-url="{{ url()->full() }}"
                        data-title="{{ $image->name }} by {{ $author->username }}"
                        data-description="{{ $image->description }}"
                        data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
                    </div>
                </div>

                @if(!empty($recentImages))
                    @if(count($recentImages) >= 9)
                    <p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
                    <div class="more-images-container">
                        @foreach($recentImages as $recentImage)
                            <div class="more-images-container-element">
                                <a href='{{url("image/".$recentImage->id)}}'>
                                    <img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
                                </a>
                            </div>
                        @endforeach
                    </div>
                    @endif
                @endif

                @if(!empty($similarImages))
                    @if(count($similarImages) >= 9)
                    <p class='similar-images'>Подобни произведения</p>
                    <div class="similar-images-container">
                        @foreach($similarImages as $similarImage)
                            <div class="similar-images-container-element">
                                <a href='{{url("image/".$similarImage->id)}}'>
                                    <img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
                                </a>
                            </div>
                        @endforeach
                    </div>
                    @endif
                @endif

                @auth
                    <div class='postComments'>
                        <form method='POST' action=''>
                            <textarea class='comment-section' name='comment'></textarea>
                            <input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
                            <input type="hidden" name="image_id" value="{{ $image->id }}">
                            <button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
                        </form>
                    </div>
                @endauth

                <div class='comments'>
                    @foreach($image->comments as $comment)
                        {{ $comment->user->username }}
                    @endforeach
                </div>

            </div>
        </div>

    </div>

<script>
    var token = '{{ Session::token() }}';
    var urlComment = '{{ route('comment') }}';
    var urlLike = '{{ route('vote') }}';
</script>
@endsection

1 个答案:

答案 0 :(得分:3)

我建议也将user关系添加到您的Comment模型中:

class Comment extends Model
{
    public function image()
    {
        return $this->belongsTo('App\Image');
    }

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

然后您可以eager load关系,然后在刀片文件中访问它们:

public function specificImage($id)
{
    $image = Image::with('comments.user')->find($id);

    return view('specificImage', ['image' => $image]);
}

然后在刀片文件中,您将得到类似的内容:

@foreach($image->comments as $comment)

    {{ $comment->user->username }}

@endforeach