我想用type_name获得响应属性,无需在表
中添加新字段。{
"status": 200,
"message": "OK",
"data": {
"id": 23,
"uuid": "9b1d33f9-0e44-4161-9936-ec41309697a5",
"sender_id": null,
"receiver_id": 2,
"type": 0,
"coin": 200,
"balance": 27000,
"description": "Topup 200 coin",
"type_name": "Topup"
}
因此,我尝试在CoinTransaction模型中创建一个名为typeName()的方法,希望可以通过with()方法调用该方法,如下所示:
$transaction = CoinTransaction::create([
'receiver_id' => auth()->user()->id,
'coin' => $request->coin,
'balance' => $predefineCoin->balance ?? 1000,
'type' => 0,
'description' => $request->description
]);
$transaction = CoinTransaction::with(['typeName'])->find($transaction->id);
但是它返回一个错误:
Error: Call to a member function addEagerConstraints() on string...
在我的CoinTransaction模型
class CoinTransaction extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function sender() {
return $this->belongsTo(User::class, 'sender_id');
}
public function receiver() {
return $this->belongsTo(User::class, 'receiver_id');
}
public function typeName() {
$typeName = null;
switch($this->type){
case 0: $typeName = 'Topup'; break;
default: $typeName = 'Unknown';
}
return $typeName;
}
}
typeName
不是relationship method
所以下面是typeName()
$coin=CoinTransaction::find($transaction->id);
dd($coin->typeName());
或
要将type_name
属性添加到现有响应中,可以使用Mutators
裁判:https://laravel.com/docs/8.x/eloquent-mutators器和写值器
所以在CoinTransaction
protected $appends = ['type_name'];
和方法
public function getTypeNameAttribute()
{
$typeName = null;
switch($this->type){
case 0: $typeName = 'Topup'; break;
default: $typeName = 'Unknown';
}
return $typeName;
}
so in controller
$transaction = CoinTransaction::find($transaction->id);