我的数据透视表上有一个模型更改器,如下所示:
当我这样保存时:
$account_transaction->subcategories()->attach($water_subcategory->id, ['amount'=>56]);
数据库显示56,而不是5600。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SubcategoryTransaction extends Model
{
protected $table = 'subcategory_transaction';
protected $fillable = ['amount'];
public function getAmountAttribute($value)
{
if ($value) {
$value = $value / 100;
return $value;
}
return null;
}
public function setAmountAttribute($value)
{
$value = $value * 100;
dd($value);
$this->attributes['amount'] = $value;
}
}
我能够使用一种在附加之前调用金额的方法来创建特征。
现在,当我像这样检索这些数据时:
return $this_month_transactions = AccountTransaction::where('account_id', $account_id)
->whereBetween('date', [ $first_of_month_date->format('Y-m-d'), $last_of_month_date->format('Y-m-d'), ])
->with('entity','subcategories')
->get();
我需要对每个金额进行一轮($ value / 100,2):
"subcategories": [
{
"id": 61,
"once_monthly": 1,
"transaction_category_id": 10,
"name": "Rent & mortgage",
"slug": "rent-mortgage",
"type": "expense",
"created_at": "2018-08-16 05:44:53",
"updated_at": "2018-08-16 05:44:53",
"pivot": {
"transaction_id": 1,
"subcategory_id": 61,
"created_at": "2018-08-16 05:44:54",
"updated_at": "2018-08-16 05:44:54",
"amount": 72500
}
}
我需要72500才能变成725.00
答案 0 :(得分:2)
只要您使用的是Laravel> = 5.5,就可以将访问器和变异器添加到数据透视模型中。
首先,更改您的SubcategoryTransaction
类以扩展Pivot
类而不是Model
,因此您应该以类似以下内容结束:
use Illuminate\Database\Eloquent\Relations\Pivot;
class SubcategoryTransaction extends Pivot {
/**
* Convert the amount from pence to pounds.
*
* @param $amount
* @return float|int
*/
public function getAmountAttribute($amount)
{
return $amount / 100;
}
/**
* Set the amount attribute to pence.
*
* @param $amount
*/
public function setAmountAttribute($amount)
{
$this->attributes['amount'] = $amount * 100;
}
}
然后在您的belongsToMany
关系中,链接另一个称为using()
的方法,将其传递给您的数据透视模型名称,例如:
public function subcategories()
{
return $this->belongsToMany(Subcategory::class)
->using(SubcategoryTransaction::class) // <-- this line
->withTimestamps()
->withPivot('amount');
}