问题
I have a model mutator on my pivot table like so:
When I save to it like this:
$account_transaction->subcategories()->attach($water_subcategory->id, ['amount'=>56]);
The database shows 56, instead of 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;
}
}
I was able to create a Trait with a method that gets called on the amount before attaching.
Now when I retrieve these data like this:
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();
I need to run the round($value/100,2) on each amount:
"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
}
}
I need 72500 to become 725.00
回答1:
As long as you're using Laravel >=5.5 you can add accessor and mutators to a pivot model.
Firstly, change your SubcategoryTransaction
class to extend the Pivot
class instead of the Model
so you should end up with something like:
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;
}
}
Then in your belongsToMany
relationships chain another method on called using()
passing it the name of your pivot model e.g.:
public function subcategories()
{
return $this->belongsToMany(Subcategory::class)
->using(SubcategoryTransaction::class) // <-- this line
->withTimestamps()
->withPivot('amount');
}
来源:https://stackoverflow.com/questions/51869877/laravel-model-mutator-not-working-when-using-attach-to-save-on-pivot-table