laravel - 雄辩的withcount不显示计数
问题描述
我从 laravel 每日https://laraveldaily.com/eloquent-withcount-get-related-records-amount/关注这个我没有收到错误但计数没有显示,当 dd $post->likes_count 我得到空值。过滤喜欢时搜索也不起作用,我想这是同一个问题。我不想使用 count() 因为我得到了 40 个查询而不是 8 个,所以对此有任何解决方案以及为什么这不起作用?
<span class="leading-none text-sm font-semibold mr-2 mt-1 text-white">{{ $post->likes_count }}</span>
<span class="leading-none text-sm font-semibold mr-2 mt-1 text-white">{{ $post->comments_count</span>
public function render()
{
return view('livewire.posts', [
'posts' => Post::withCount(['comments', 'likes'])->orderBy('created_at', 'DESC')->where('user_id', auth()->user()->id)->paginate(5)
]);
}
搜索:
public function index(Request $request)
{
$search = request()->input('title');
$posts = Post::query()->latest();
if ($search) {
$posts->where('title', 'LIKE', '%' . request()->title. '%');
} elseif ($request->has('likes')) {
$posts->withCount('likes')->orderByDesc('likes_count');
} elseif ($request->has('latest')) {
$posts->orderByDesc('created_at');
} elseif ($request->has('follow')) {
$posts->whereIn('user_id', $request->user()->following()->pluck('users.id'));
}
return view('welcome', [
'posts' => $posts->paginate(12)
]);
}
后模态:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Storage;
use Spatie\Image\Image;
use Spatie\Image\Manipulations;
class Post extends Model
{
use HasFactory;
use Notifiable;
protected $guarded = [];
protected $casts = [
'active' => 'boolean',
];
public function likedBy(User $user)
{
return $this->likes->contains('user_id', $user->id);
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function likes()
{
return $this->hasMany(Like::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function incrementReadCount()
{
$this->increment('reads');
}
public function publish()
{
$this->active = true;
$this->save();
}
public function unpublish()
{
$this->active = false;
$this->save();
}
public function storeImage(?UploadedFile $image)
{
if ($image) {
if ($this->image) {
Storage::delete($this->image);
}
$this->image = $image->store('public/photos');
Image::load(Storage::path($this->image))
->fit(Manipulations::FIT_CONTAIN, 718, 718)
->save();
$this->save();
}
}
public function getImageUrlAttribute()
{
return $this->image
? Storage::url($this->image)
: url('img/default_post_cover.jpg');
}
}
解决方案
推荐阅读
- excel - 在 Excel 电子表格中查找并用大写文本替换文本
- css - 隐藏标签谷歌地图
- java - 如何在 Java 应用程序中使用 hikaricp
- python - NetworkX / Pandas - 无法将节点的度数输出到 .txt 文件中(错误消息)
- wpf - WPF中的多个并行GridSplitter
- c - C 客户端服务器与
- android - 应用程序ID更改后React Native Android应用程序找不到图像
- python - 取消 Gtk.TreeView 中某些特定项目的拖放
- ios - 仅当从 Testflight 下载时,iOS 应用程序才会在 iOS 12 beta 9 及更早版本上崩溃
- c# - google chrome 浏览器 - C# 中的读/写设置