【发布时间】:2019-07-08 21:59:17
【问题描述】:
这是我第一次使用 laravel nova,我想将我的数据保存在 2 个表中,第一次保存基本数据,第二次保存历史数据。在我的 Item 表中,我保存了 id、代码、名称、价格,我的 Item_Codes 表保存了 item_id 和代码,我知道了。我的问题是在 Item_Codes 中保存数据时会保存两次
我用的是 Laravel Observer,这是我保存的 ItemObserver 函数
public function saved(Item $item)
{
DB::table('item_codes')->insert(
[
'item_id' => $item->id,
'code' => $item->current_code,
'created_by' => $item->created_by,
]
);
}
这是我的物品资源
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Original code', 'original_code')
->sortable()
->rules('required', 'string', 'max:255')
->hideFromIndex(),
Text::make('Current code', 'current_code')
->sortable()
->rules('required', 'string', 'max:255'),
Text::make('Name', 'name')
->sortable()
->rules('required', 'string', 'max:255'),
Textarea::make('Description', 'description')
->rules('required')
->creationRules('required', 'string'),
Number::make('Cost', 'cost')
->sortable()
->rules('required')
->min(1),
Number::make('Minimum price', 'minimum_price')
->sortable()
->rules('required')
->min(1),
Text::make('ABCD Classification', 'abcd_classification')
->sortable()
->rules('required', 'string')
->hideFromIndex()
->hideWhenCreating()
->hideWhenUpdating(),
BelongsToMany::make('Categories'),
new Panel('Stock', $this->stockFields()),
new Panel('Tracking', $this->trackingFields()),
];
}
这是我的物品模型
class Item extends Model{
/**
* The attributes that aren mass assignable.
*
* @var array
*/
protected $fillable = [
'original_code',
'current_code',
'name',
'description',
'current_stock',
'unavailable_stock',
'cost',
'minimum_price',
'abcd_classification'
];
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [
'created_by',
'updated_by'
];
/**
*
* Providers
*
* Returns the items providers
*
* @return collection
*/
public function providers()
{
return $this->belongsToMany('App\Models\Provider');
}
/**
*
* Categories
*
* Returns the items categories
*
* @return collection
*/
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
}
对不起,我的英语不好,我希望你的回答
【问题讨论】:
-
您想在创建、更新还是两者都这样做?
-
我只是希望当我在我的 items_tables 中保存一个项目时,这也会保存在 item_codes 中
-
问题是
saved方法在created和updated上都被调用。我首先会怀疑周围的事情。如果只在创建对象时需要它,请将其放在方法体creatednot saved。 -
我尝试使用
created方法,这也被保存了两次 -
在应用程序某处被触发两次。仔细检查代码库(您编写的代码)。你使用一些事件/监听器对吗?也许在那里?
标签: php laravel laravel-nova