Laravel - Duplicate record to other database - eloquent model - laravel-8
I am trying to duplicate rows with a given product_id and a given cart_product_id from database mysqlProducts - table ind_products to database mysqlOrders - table cart_ind_products.
My models:
class IndProduct extends Model {
use HasFactory;
protected $connection = 'mysqlProducts';
protected $table = "ind_products";
protected $fillable = [
'product_id',
'name',
'category',
'subcategory',
'description',
'price_VAT_excl_per_unit',
'price_VAT_incl_per_unit',
'weight',
'breed',
'kind',
'age',
'bio',
'grass_fed',
'drying_time',
'nr_of_pieces',
'lifestyle',
'part_of_animal',
'confirmed',
'saved',
];
//an individual product belongs to a product
public
function products() {
return $this - > setConnection('mysqlProducts') - > belongsTo(Product::class, 'product_id', 'id');
}
}
class CartIndProduct extends Model {
use HasFactory;
protected $connection = 'mysqlOrders';
protected $table = "cart_ind_products";
protected $fillable = [
'cart_product_id',
'product1_id',
'name',
'category',
'subcategory',
'description',
'price_VAT_excl_per_unit',
'price_VAT_incl_per_unit',
'weight',
'breed',
'kind',
'age',
'bio',
'grass_fed',
'drying_time',
'nr_of_pieces',
'lifestyle',
'part_of_animal',
'confirmed',
'saved',
];
//A cart individual product belongs to a cart product
public
function cart_products() {
return $this - > setConnection('mysqlOrders') - > hasOne(CartProduct::class, 'cart_product_id', 'id');
}
}
CartIndProductController:
public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
$ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get() - > toArray();
foreach($ind_products as $ind_product) {
CartIndProduct::on('mysqlOrders') - > insert($ind_product);
}
return response() - > json([
"status" => 1,
"message" => "Cart individual products registered successfully in database.",
], 200);
}
I get the following error:
"SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2022-10-28T19:54:12.000000Z' for column 'created_at' at row 1 (SQL: insert into cart_ind_products (id, name, category, subcategory, description, price_VAT_excl_per_unit, price_VAT_incl_per_unit, weight, created_at, updated_at, product_id, breed, kind, age, bio, grass_fed, drying_time, nr_of_pieces, lifestyle, part_of_animal, confirmed, saved) values (656, ?, Aardappelen, ?, ?, 0.00, 0.00, ?, 2022-10-28T19:54:12.000000Z, 2022-10-28T19:54:12.000000Z, 903, bjbg, ?, ?, 0, ?, ?, ?, ?, ?, 1, 1))"
I also tried the following, but also without luck..
public function createCartIndProducts(Request $request, $cart_product_id, $product_id) {
$ind_products = IndProduct::on('mysqlProducts') - > where('product_id', '=', $product_id) - > get();
foreach($ind_products as $ind_product) {
$cart_ind_product = IndProduct::on('mysqlProducts') - > $ind_product - > replicate() -
> fill(
['cart_product_id' => $cart_product_id, ]
);
$cart_ind_product - > CartIndProduct::on('mysqlOrders') - > save();
}
return response() - > json([
"status" => 1,
"message" => "Cart individual products registered successfully in database.",
// "data" => $cart_ind_products,
], 200);
}
This time I recieve the following error:
"Property [{"id":656,"name":null,"category":"Aardappelen","subcategory":null,"description":null,"price_VAT_excl_per_unit":"0.00","price_VAT_incl_per_unit":"0.00","weight":null,"created_at":"2022-10-28T19:54:12.000000Z","updated_at":"2022-10-28T19:54:12.000000Z","product_id":903,"breed":"bjbg","kind":null,"age":null,"bio":0,"grass_fed":null,"drying_time":null,"nr_of_pieces":null,"lifestyle":null,"part_of_animal":null,"confirmed":1,"saved":1}] does not exist on the Eloquent builder instance.",
What am I doing wrong?
Related
How to reduce "Masuk" automatically using $appends variable if I add data
I'm fetching data from the warehouse table using the $appends variable, I want the "Masuk" column to be automatically reduced when I add the next data, but every time I add a data field, it's always fetched from the warehouse table, right? So how to reduce it? what to change in my code? My views: https://ibb.co/mT86hz7 My views My serving model : protected $visible = ['barang_keluar']; protected $appends = ['barang_keluar']; public function warehouse() { return $this->belongsTo(Warehouse::class, 'warehouse_id')->withDefault(['barang_keluar' => '0']); } public function setTotalAttribute() { return $this->attributes['total'] = $this->attributes['qty'] + $this->attributes['sisa_semalam'] + $this->attributes['sisa_today'] + $this->attributes['rusak'] + $this->attributes['double']; } // ==== ambil data barang keluar dari warehouse untuk dijadikan virtual field barang masuk di tabel serving === public function getBarangKeluarAttribute() { return $this->warehouse->barang_keluar + $this->attributes['sisa_semalam'] + $this->attributes['sisa_today'] - $this->attributes['qty']; } My warehouse model: public function serving() { return $this->hasOne(Serving::class)->withDefault([ 'nm_bahan' => '-', 'sisa_semalam' => '0', 'sisa_today' => '0', 'rusak' => '0', 'double' => '0', 'qty' => '0', 'total' => '0', 'ket' => '-']); } public function setSaldoAttribute() { return $this->attributes['saldo'] = $this->attributes['stok_awal'] + $this->attributes['barang_masuk'] - $this->attributes['barang_keluar']; }
Implement Phalcon 4 Database Existence validator (similar to Uniqueness)
Often I need to validate if given value is existing in certain column (attribute) of a table (model). This can be useful in foreign keys of a model, to check if the given values exists. Most probably the validation logic can be mostly the same as for Uniqueness, except the comparison here can be something like > 0. A possible usage scenario could be like below: $validator->add( 'organization_id', new ExistenceOnDbValidator( [ 'model' => Organization::class, 'expr'=> ' id = %s ', 'excludeNullValue'=> true, 'message' => 'Organization does not exist.', ] ) );
Finally I implemented myself a validator called ExistenceOnDbValidator and it works fine. Usage $validator = new Validation(); $validator->add( 'organization_id', new ExistenceOnDbValidator( [ 'model' => Organization::class, 'expr' => ' id = %s ', 'ignoreNullValue' => false, 'message' => 'Selected organization does not exist.', ] ) ); Implenentation use Phalcon\Messages\Message; use Phalcon\Validation; use Phalcon\Validation\AbstractValidator; use Phalcon\Validation\ValidatorInterface; class ExistenceOnDb extends AbstractValidator implements ValidatorInterface { public function validate(Validation $validator, $attribute): bool { $expr = $this->getOption('expr'); $model = $this->getOption('model'); $value = $validator->getValue($attribute); $ignoreNullValue = true; if ($this->hasOption('ignoreNullValue')) { $ignoreNullValue = $this->getOption('ignoreNullValue'); } if ((is_null($value) || empty($value)) && $ignoreNullValue == true) { return true; } $expr = sprintf( $expr, $value, ); $result = $model::findFirst($expr); if ((is_null($result) || empty($result))) { $message = $this->getOption('message'); $validator->appendMessage(new Message($message)); return false; } return true; } }
override searchProvider.php does not work
Create : override/modules/ps_facetedsearch/src/Product/SearchProvider.php Create : override/modules/ps_facetedsearch/ps_facetedsearch.php Delete the cache manually Version : 1.7.6.4 override SearchProvider.php doesn't work override ps_facetedsearch.php work I need to delete 2 types of sorting ... into SearchProvider.php:getAvailableSortOrders() but I never go through the overloaded function if (!defined('PS_VERSION')) exit; class SearchProviderOverride extends SearchProvider { /** * #return array */ public function getAvailableSortOrders() { $sortPosAsc = new SortOrder('product', 'position', 'asc'); $sortPriceAsc = new SortOrder('product', 'price', 'asc'); $sortPriceDesc = new SortOrder('product', 'price', 'desc'); $translator = $this->module->getTranslator(); die('hello not world!'); return [ $sortPosAsc->setLabel( $translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop') ), $sortPriceAsc->setLabel( $translator->trans('Price, low to high', [], 'Shop.Theme.Catalog') ), $sortPriceDesc->setLabel( $translator->trans('Price, high to low', [], 'Shop.Theme.Catalog') ), ]; } }```
"getAvailableSortOrders" is a private method. You are probably only hidding the private method with your public one. You should override the "runQuery" method since it's the only one that uses "getAvailableSortOrders". This way your overriden "runQuery" will call the appropriate "getAvailableSortOrders" method. And finally, you can make your "getAvailableSortOrders" private since its only meant to be used in this class. if (!defined('PS_VERSION')) exit; class SearchProviderOverride extends SearchProvider { /** * #return array */ private function getAvailableSortOrders() { $sortPosAsc = new SortOrder('product', 'position', 'asc'); $sortPriceAsc = new SortOrder('product', 'price', 'asc'); $sortPriceDesc = new SortOrder('product', 'price', 'desc'); $translator = $this->module->getTranslator(); die('hello not world!'); return [ $sortPosAsc->setLabel( $translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop') ), $sortPriceAsc->setLabel( $translator->trans('Price, low to high', [], 'Shop.Theme.Catalog') ), $sortPriceDesc->setLabel( $translator->trans('Price, high to low', [], 'Shop.Theme.Catalog') ), ]; } /** * #param ProductSearchContext $context * #param ProductSearchQuery $query * * #return ProductSearchResult */ public function runQuery( ProductSearchContext $context, ProductSearchQuery $query ) { $result = new ProductSearchResult(); // extract the filter array from the Search query $facetedSearchFilters = $this->filtersConverter->createFacetedSearchFiltersFromQuery($query); $context = $this->module->getContext(); $facetedSearch = new Search($context); // init the search with the initial population associated with the current filters $facetedSearch->initSearch($facetedSearchFilters); $orderBy = $query->getSortOrder()->toLegacyOrderBy(false); $orderWay = $query->getSortOrder()->toLegacyOrderWay(); $filterProductSearch = new Filters\Products($facetedSearch); // get the product associated with the current filter $productsAndCount = $filterProductSearch->getProductByFilters( $query->getResultsPerPage(), $query->getPage(), $orderBy, $orderWay, $facetedSearchFilters ); $result ->setProducts($productsAndCount['products']) ->setTotalProductsCount($productsAndCount['count']) ->setAvailableSortOrders($this->getAvailableSortOrders()); // now get the filter blocks associated with the current search $filterBlockSearch = new Filters\Block( $facetedSearch->getSearchAdapter(), $context, $this->module->getDatabase() ); $idShop = (int) $context->shop->id; $idLang = (int) $context->language->id; $idCurrency = (int) $context->currency->id; $idCountry = (int) $context->country->id; $idCategory = (int) $query->getIdCategory(); $filterHash = md5( sprintf( '%d-%d-%d-%d-%d-%s', $idShop, $idCurrency, $idLang, $idCategory, $idCountry, serialize($facetedSearchFilters) ) ); $filterBlock = $filterBlockSearch->getFromCache($filterHash); if (empty($filterBlock)) { $filterBlock = $filterBlockSearch->getFilterBlock($productsAndCount['count'], $facetedSearchFilters); $filterBlockSearch->insertIntoCache($filterHash, $filterBlock); } $facets = $this->filtersConverter->getFacetsFromFilterBlocks( $filterBlock['filters'] ); $this->labelRangeFilters($facets); $this->addEncodedFacetsToFilters($facets); $this->hideUselessFacets($facets, (int) $result->getTotalProductsCount()); $facetCollection = new FacetCollection(); $nextMenu = $facetCollection->setFacets($facets); $result->setFacetCollection($nextMenu); $result->setEncodedFacets($this->facetsSerializer->serialize($facets)); return $result; } }
Insert multi record to database with yii2
I want to insert many record to database in one action. In this controller I used foreach for insert to database, but just the last record inserts to database, I don't know why. I want to insert all the record to database. My controller: if (isset($_POST['month'])) { $name = $_POST['month']; $price = $_POST['Request']; $i = 0; foreach ($name as $month) { $model->month = $month; $model->price = $price['price']; $model->save(false); $i++; } $pay_info = [ 'cost' => $price['price'], 'title' => 'title']; return $this->render('payment', ['pay_info' => $pay_info]); }
A simple way is based on the fact you should create a new model in you foreach for each instance you want save (your controller code is not complete so i can't know your model ) if (isset($_POST['month'])) { $name = $_POST['month']; $price = $_POST['Request']; $i = 0; foreach ($name as $month) { $model = new YourModel(); /* here */ $model->month = $month; $model->price = $price['price']; $model->save(false); $i++; } $pay_info = [ 'cost' => $price['price'], 'title' => 'title']; return $this->render('payment', ['pay_info' => $pay_info]); } but i siggest to explore also the batchInsert command http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail For batch insert you can build an asscociative array with month and price eg: $my_array= [ ['January', 30], ['Febrary', 20], ['March', 25], ] \Yii::$app->db->createCommand()-> batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute();
get values between two dates in silverstripe
i have added two date fields. i want to retrieve the data between those two table.PaymentDate and ChequePostedDate are two fields. so i need to get the rows between two dates. simply search content have two date fields. i want to retrieve the rows(data) between those two dates public function __construct($modelClass, $fields = null, $filters = null) { $fields = new FieldList(array( DateField::create('PaymentDate','Payment Date : from') ->setConfig('dateformat', 'yyyy-MM-dd') ->setConfig('showcalendar', true) ->setAttribute('placeholder','YYYY-MM-DD') ->setDescription(sprintf( _t('FormField.Example', 'e.g. %s', 'Example format'), Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd')) )), DateField::create('ChequePostedDate','cr Date : to') ->setConfig('dateformat', 'yyyy-MM-dd') ->setConfig('showcalendar', true) ->setAttribute('placeholder','YYYY-MM-DD') ->setDescription(sprintf( _t('FormField.Example', 'e.g. %s', 'Example format'), Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd')) )), )); $filters = array( 'PaymentDate' => new PartialMatchFilter('PaymentDate'), 'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'), ); parent::__construct($modelClass, $fields, $filters); } public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) { $dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery); $params = is_object($searchParams) ? $searchParams->getVars() : $searchParams; $query = $dataList->dataQuery(); if(!is_object($searchParams)) { if (isset($params['PaymentDate'])&& $params['ChequePostedDate'] ) { $query->where('`PaymentNote`.PaymentDate BETWEEN \''.$params['PaymentDate'].' \' AND \''.$params['ChequePostedDate'].'\''); } } return $dataList->setDataQuery($query); } }
You can also use WithinRangeFilter something like the following, but you need to use the setMin(), setMax() methods as per this forum response: https://www.silverstripe.org/community/forums/form-questions/show/11685 public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) { $dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery); $params = is_object($searchParams) ? $searchParams->getVars() : $searchParams; $query = $dataList->dataQuery(); if(!is_object($searchParams)) { if (!empty($params['PaymentDate'] && !empty($params['ChequePostedDate'])) { return $dataList->filter('PaymentDate:WithinRange', [$params['PaymentDate'], $params['ChequePostedDate']]); } } return $dataList; }
i solved it.. simply remove $filters $filters = array( // 'PaymentDate' => new PartialMatchFilter('PaymentDate'), //'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'), ); then it works