对 Laravel 中的循环实例进行排序

Sort instances of a loop in Laravel

您好,过去几周我一直在学习 Laravel。虽然我遇到了根据这个值对这个循环的每个实例进行排序的问题 ----> $post->user->receivedUpvotes->count() - $post->user->receivedDownvotes->count()

@foreach($posts->unique('user_id') as $post)   
  <a href="{{ route('users.posts', $post->user) }}" class="font-bold text-xl">
    {{ $post->user->name }}
  </a>
  <p class="mb-4">
    <span class="mr-3 text-gray-600">Karma Gained: </span>
    <span class="text-green-700 font-semibold">
      {{ $post->user->receivedUpvotes->count() - $post->user->receivedDownvotes->count() }}
    </span>
  </p> 
@endforeach

我一直在寻找对它们进行排序的解决方案,因为它们的值不在数据库中

我的模型是这样的

User.php

public function posts()
{
    return $this->hasMany(Post::class);
}

public function upvotes()
{
    return $this->hasMany(Upvote::class);
}

public function receivedUpvotes()
{
    return $this->hasManyThrough(Upvote::class, Post::class);
}

public function downvotes()
{
    return $this->hasMany(Downvote::class);
}

public function receivedDownvotes()
{
    return $this->hasManyThrough(Downvote::class, Post::class);
}

Post.php

public function upvotedBy(User $user)
{
    return $this->upvotes->contains('user_id', $user->id);
}

public function downvotedBy(User $user)
{
    return $this->downvotes->contains('user_id', $user->id);
}

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

public function upvotes()
{
    return $this->hasMany(Upvote::class);
}

public function downvotes()
{
    return $this->hasMany(Downvote::class);
}

并且 Upvote.php 和 Downvote.php 都有这个

use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id'
    ];

这是我的控制器DashboardController.php,目前我只放它来显示最新的posts

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
    }

    public function index(Post $post)
    {
        $posts=Post::latest()->with(['user','upvotes'])->get();
        return view ('dashboard',['posts'=>$posts]);    
    }        
}

在User.php中添加

public function getNetVotesAttribute() 
{
    return $this->receivedUpvotes()->count() - $this->receivedDownvotes()->count(); 
} 

那么您可以使用该功能对您的用户进行排序,或者如果您将“netVotes”添加到User.php中的$appends数组,您可以直接使用netVotes进行排序。例如

$posts = Post::all()->sortBy(function($post) { 
    return $post->user->netVotes; 
}); 

或者如果您没有添加到 $appends 数组,

$posts = Post::all()->sortBy(function($post) { 
    return $post->user->getNetVotesAttribute(); 
});