Reputation: 622
I am working in laravel 5.4 (stock management system) and have dynamic table means table generate on create new store. Each store have its own stock table with his id like store_8_stock
. I create StoreStock
model and when set table from controller its not working correctly:
$storeId = $item['store_id'];
unset($item['barcode']);
TransferList::create($item);
$insertStock = new StoreStock;
$insertStock->setTable('store_'.$storeId.'_stock');
$stock = $insertStock->where('item_id',$item['item_id'])->first();
if($stock != null){
$stock->qty = $stock->qty + $item['qty'];
$stock->save();
}else{
unset($item['item_name']);
unset($item['store_id']);
$insertStock->create($item);
}
for $stock = $insertStock->where('item_id',$item['item_id'])->first();
its working fine but when its coming on $insertStock->create($item);
its showing error store_stocks table or view not found
$item Contains
array:11 [▼
"barcode" => "8901023007446"
"item_id" => 2
"item_name" => "My new item"
"mrp" => 12.0
"sale_price" => 60.0
"purchase_price" => 50.0
"qty" => "2"
"free_item_name" => ""
"product_vat" => 0.0
"vat_status" => 0
"store_id" => "8"
]
can any one please tell me what is wrong in my code?
Upvotes: 1
Views: 280
Reputation: 4303
This error and errors like it come down to the following reason:
some methods like all() create a new model instance in the background.
So when a new instance is created your setTable is gone.
The non static use of methods prefend this:
//wont work
Model::all()
// will work
$model->get()
Upvotes: 0
Reputation: 111859
This is because when you use create
under the hood the newInstance()
method is fired and the new instance of object has original property as defined in your model.
Probably you should use for such case something like this:
$insertStock->fill($item)->save();
to make it work.
Upvotes: 3