laravel 模型追加append 属性使用
1、如果你的需要的数据,是根据数据库中的某个值,计算出来。可以appends中增加该属性,再定义一个访问器返回对应的结果
注:定义在模型类上,对所有的模型数据都会增加该属性。
这里的 getAvailableCreditAttribute 方法名中 get 和 Attribute 是固定写法,真正在模型中的名称是由 AvailableCredit决定,命名一般是驼峰写法,一个单词时在 ORM 模型中就是那个单词的小写
<?php namespace App\Models\Member; use App\Models\Company\Company; use App\Models\User; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles; use App\Notifications\ResetPasswordNotification; class Member extends Authenticatable { protected $table = 'members'; protected $fillable = [ 'id', 'identity', 'username', 'phone', 'email', 'name', 'password', 'remember_token', 'company_name', 'company_id', 'status', 'is_deposit', 'pre_deposit', 'credit_limit', 'spending', 'account_periods', 'user_id', 'manage_id', 'open_id', 'type', 'created_at', 'updated_at', 'salt', 'pid', 'labgle_id', 'from', 'note' ]; protected $hidden = ['password']; protected $appends = ['available_credit', 'arrear']; public function getAvailableCreditAttribute() { return clearZero(number_format($this->pre_deposit + $this->credit_limit - $this->spending, 2, '.', '')); } public function getArrearAttribute() { $arrear = clearZero(number_format($this->spending - $this->pre_deposit, 2, '.', '')); return $arrear > 0 ? $arrear : 0; } public function getPreDepositAttribute($value): float { return floatval($value); } public function getCreditLimitAttribute($value): float { return floatval($value); } public function getSpendingAttribute($value): float { return floatval($value); } public function company() { return $this->hasOne(Company::class, 'id', 'company_id'); } public function user() { return $this->hasOne(User::class, 'id', 'user_id'); } static $type = [ '1' => '普通用户', '11,12' => '集团用户及子账户', '21' => '校园用户' ]; }
<div class="top"> <h2>{{auth('member')->user()->company_name}}</h2> <p>{{auth('member')->user()->name}}</p> <span>预存款余额:¥{{auth('member')->user()->available_credit}}</span> </div>