php - Laravel 模型 $appends 或 $attribute 不适用于关系
问题描述
我有 User.php,重要的部分是......
public function posts()
{
return $this->hasMany('App\Models\Post', 'post_author', 'ID')
->where('post_status', 'publish')->latest('App\Models\Post'::CREATED_AT);
}
Post.php
protected $appends = ['vote_count'];
public function getVoteCountAttribute()
{
$vote_count = $this->postMeta()
->where('meta_key', '=', 'et_vote_count')->first();
$this->attributes['vote_count'] = !empty($vote_count) ? $vote_count->meta_value : 0;
// return !empty($vote_count) ? $vote_count : 0;
}
我希望在vote_count
加载模型时加载该属性。
教师控制器.php
$sort_by_vote_count = $teacher->posts->sortByDesc(function ($post, $key) {
dd($post);
return $post->vote_count;
});
然后我转储了帖子,但我没有看到 vote_count 属性,所以我无法按 vote_count 排序。
解决方案
推荐阅读
- python-3.x - 如何在 Python 中增加默认变量长度
- arrays - Ruby 计算数组中的整数
- docker - 如何在 Docker 上运行 FHIR?
- selenium - 自动关闭当前工作窗口正在退出驱动程序
- python-3.x - 从调试器执行单个操作码
- apache - 使用 .htaccess 重写合成器的 url
- html - WordPress 未显示 SVG 笔划路径
- r - 闪亮的输入附加数据帧
- python - TensorFlow flatten vs numpy flatten 函数对机器学习训练的影响
- python - PyMongo:如何使用聚合并将结果存储到另一个集合?