首页 > 解决方案 > 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 排序。

标签: phplaravel

解决方案


推荐阅读