如何使用关系和一些逻辑附加列数据库结果 laravel

How to appending a column db result with relation and some logic laravel

我这里有个问题,我想从关系的结果中添加一列,即百分比列,这一列是pagebook / pageread * 100的结果 这是我想要的结果数据库

"id": 2,
    "id_book": 2,
    "id_user": 2,
    "pageread": 120,
    "books": {
                "id": 2,
                "pagebook":125
             }
    "percentage":96

这是我在控制器中的代码

$book= Read::with('books.authors')->where('id_user',$user->id)->get();

这是我在模型中的代码

public function books()
    {
        return $this->belongsTo(Book::class,'id_book','id');
    }

你可以在模型中做到:

class YourModel ...{
    protected $appends = ['percentage'];
    public function getPercentageAttribute()
    {
        return /* the calculation that you need */
    }
}
 protected $appends = ['percentage'];
    public function getPercentageAttribute()
    {
        $read= $this->pageread;
        $book= $this->books->pagebook
        return $read/$book*100


    }