I'm using a form for an advanced search. The form inputs are representative of the data in the elasticsearch index. My model receives an array of filter terms and query terms.
$data = array(
'Filter' => array(
'FilerId' => 14592
),
'Query' => array(
'FiledDate' => '2015-08-06',
),
);
I'm using a foreach loop to create the filter and query
foreach ($data['Filter'] AS $field => $value) {
$filter = new \Elastica\Filter\Term();
$filter->setTerm($field, $value);
$filterArray[] = $filter;
}
foreach ($data['Query'] AS $field => $value) {
$query = new \Elastica\Query\QueryString($value);
$query->setDefaultOperator('AND')
->setDefaultField($field);
$queryArray[] = $query;
}
$query = new \Elastica\Query();
$query
->setFields(['TranId'])
->setQuery($queryArray)
->setFilter($filterArray);
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);
I am getting an error and I can't find the reason why?
Here is some updated code. I'm getting results but not what I thought I should get.
$boolFilter = new \Elastica\Filter\BoolFilter();
foreach ($data['Filter'] AS $field => $value) {
$term = new \Elastica\Filter\Term();
$term->setTerm($field, $value);
$boolFilter->addMust($term);
}
$boolQuery = new \Elastica\Query\BoolQuery();
foreach ($data['Query'] AS $field => $value) {
$match = new \Elastica\Query\Match();
$match->setFieldQuery($field, $value)
->setFieldAnalyzer($field, 'whitespace')
->setFieldOperator($field, 'AND');
$boolQuery->addMust($match);
}
$query = new \Elastica\Query();
$query
->setFields(['TranId'])
->setQuery($boolQuery)
->setFilter($boolFilter);
//print $error->getError();
print "<pre>";
print_r ($query->toArray());
print "</pre>";
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);
Alright! I needed to add the Standard analyzer instead of the whitespace analyzer. The whitespace analyzer works but only breaks the phrase up on spaces. The standard analyzer breaks the phrase up and make the case lower.
https://www.elastic.co/guide/en/elasticsearch/guide/current/analysis-intro.html#analyze-api
$boolFilter = new \Elastica\Filter\BoolFilter();
foreach ($data['Filter'] AS $field => $value) {
$term = new \Elastica\Filter\Term();
$term->setTerm($field, $value);
$boolFilter->addMust($term);
}
$boolQuery = new \Elastica\Query\BoolQuery();
foreach ($data['Query'] AS $field => $value) {
$match = new \Elastica\Query\Match($value);
$match->setFieldQuery($field, $value);
$match->setFieldAnalyzer($field, 'standard');
$boolQuery->addMust($match);
}
$filterQuery = new \Elastica\Query\Filtered();
$filterQuery->setFilter($boolFilter);
$filterQuery->setQuery($boolQuery);
$query = new \Elastica\Query($filterQuery);
$query->setFields(['TranId']);
print "<pre>";
print_r ($query->toArray());
print "</pre>";
$search->setQuery($query);
$numberOfEntries = $search->count();
$comma_separated = 0;
if ($numberOfEntries) {
foreach ($search->scanAndScroll() as $scrollId => $resultSet) {
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
foreach ($results as $result) {
$fields = $result->getFields('TransId');
$transid[] = $fields['TranId'][0];
} // ... handle Elastica\ResultSet
}
$comma_separated = implode(", ", $transid);
}
return array('transactions' => $comma_separated, 'total' => $totalResults);
Related
I'm an elementary web developer, I'm facing a problem. Please help me solve this. I'm creating both row and column dynamic. for save() is fine. But for update, only name is updated and other item
quantities cannot. Here is my codes.
//for save()
public function stockAdd(Request $request)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$user_id = Auth::user()->user_id;
$stock_id = random_int(100000, 999999);
$stocks = new Stocks();
$stocks->stock_id = $stock_id;
$stocks->owner_id = $user_id;
$stocks->stock_name = request()->stock_name;
$stocks->my_stock = 0;
$stocks->disable = 0;
$stocks->save();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
$stockitems = new StockItems();
$stockitems->stock_id = $stock_id;
$stockitems->product_id = $product->product_id;
$stockitems->owner_id = $user_id;
if(request()->$product_id > 0){
$stockitems->count = request()->$product_id;
}else{
$stockitems->count = 0;
}
$stockitems->save();
}
}
}
return redirect()->back()->with('successAddMsg','Successfully Added');
}
//for update()
public function stockUpdate(Request $request, $id)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$stock = Stocks::findOrFail($id);
$stock->stock_name = request()->stock_name;
$stock->my_stock = 0;
$stock->disable = 0;
$stock->update();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
//dd($product_id);
$stockitemitems = DB::table("stock_items")->select("*")->where("owner_id",Auth::user()->user_id)->where("stock_id",$stock->stock_id)->get();
$stockitems->count = $request->input($product_id);
$stockitems->update();
}
}
}
return redirect(route('user.stock-list'))->with('successAddMsg','Successfully Added');
}
The problem shows like this "Creating default object from empty value"
I need bulk insert in subscriber table and subscriber field table in which data comes from CSV file.
The subscriber table need the only email and subscriber fields table need subscriber id from subscriber table, field id from field table and other CSV fields.
So, I write this code for this job and here a lot of foreach loop, that's why it takes a lot of time for execute when I insert a large CSV file.
Now, Any possible to optimize this code?
Here is my code :
$emails = array();
foreach ($data as $item) {
array_push($emails, $item['email']);
}
$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();
//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
$exists_mail[$item->email] = true;
}
//get subscriber unique key
$subscriber_uid = array();
//get all field value
$total_field = array();
//bulk insert in subscribers table
$subscriberBatch = array();
foreach ($data as $item) {
if (!isset($exists_mail[$item['email']])) {
$column['uid'] = uniqid();
$column['mail_list_id'] = $this->id;
$column['email'] = $item['email'];
$column['status'] = Subscriber::STATUS_SUBSCRIBED;
$column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;
array_push($subscriberBatch, $column);
array_push($subscriber_uid, $column['uid']);
$fieldKey['uid'] = $column['uid'];
foreach ($fields as $field) {
$fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
}
array_push($total_field, $fieldKey);
}
}
Subscriber::insert($subscriberBatch);
//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')->whereIn('uid', $subscriber_uid)->get()->toArray();
foreach ($totalSubscriber as $index => $subscriber) {
$total_field[$index]['subscriber_id'] = $subscriber['id'];
}
$fieldBatch = array();
foreach ($total_field as $item) {
foreach ($fields as $field) {
$fieldColumn['subscriber_id'] = $item['subscriber_id'];
$fieldColumn['field_id'] = $field['id'];
$fieldColumn['value'] = $item[Str::lower($field['tag'])];
array_push($fieldBatch, $fieldColumn);
}
}
SubscriberField::insert($fieldBatch);
//set all email in a array
$emails = array();
foreach ($data as $item) {
array_push($emails, $item['email']);
}
$exists_mail = array();
$subscribers = Subscriber::whereIn('email', $emails)
->where('mail_list_id', $this->id)
->pluck('email')
->toArray();
//get subscriber unique key
$subscriber_uid = array();
//get all field value
$total_field = array();
//bulk insert in subscribers table
$subscriberBatch = array();
foreach ($data as $item) {
if(!in_array($item['email'], $subscribers)){
$column['uid'] = uniqid();
$column['mail_list_id'] = $this->id;
$column['email'] = $item['email'];
$column['status'] = Subscriber::STATUS_SUBSCRIBED;
$column['subscription_type'] = Subscriber::SUBSCRIPTION_TYPE_IMPORTED;
array_push($subscriberBatch, $column);
array_push($subscriber_uid, $column['uid']);
$fieldKey['uid'] = $column['uid'];
foreach ($fields as $field) {
$fieldKey[Str::lower($field['tag'])] = $item[Str::lower($field['tag'])];
}
array_push($total_field, $fieldKey);
}
}
Subscriber::insert($subscriberBatch);
//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();
$fieldBatch = array();
foreach ($totalSubscriber as $index => $subscriber) {
$total_field[$index]['subscriber_id'] = $subscriber['id'];
}
foreach ($total_field as $item) {
foreach ($fields as $field) {
$fieldColumn['subscriber_id'] = $item['subscriber_id'];
$fieldColumn['field_id'] = $field['id'];
$fieldColumn['value'] = $item[Str::lower($field['tag'])];
array_push($fieldBatch, $fieldColumn);
}
}
SubscriberField::insert($fieldBatch);
I remove below code and use pluck
$subscribers = Subscriber::select('email')->whereIn('email', $emails)->where('mail_list_id', $this->id)->get();
//check exists mail in database
$exists_mail = array();
foreach ($subscribers as $item) {
$exists_mail[$item->email] = true;
}
We more optimize and we can remove below code
foreach ($total_field as $item) {
foreach ($fields as $field) {
$fieldColumn['subscriber_id'] = $item['subscriber_id'];
$fieldColumn['field_id'] = $field['id'];
$fieldColumn['value'] = $item[Str::lower($field['tag'])];
array_push($fieldBatch, $fieldColumn);
}
}
Like:
//bulk insert in subscriber fields table
$totalSubscriber = Subscriber::select('id')
->whereIn('uid', $subscriber_uid)
->get()
->toArray();
$fieldBatch = array();
foreach ($totalSubscriber as $index => $subscriber) {
//$total_field[$index]['subscriber_id'] = $subscriber['id'];
foreach ($fields as $field) {
$fieldColumn['subscriber_id'] = $subscriber['id'];
$fieldColumn['field_id'] = $field['id'];
$fieldColumn['value'] = $item[Str::lower($field['tag'])];
array_push($fieldBatch, $fieldColumn);
}
}
But I don't know what type of data in $fields array if you provide field array the I will try more optimize.
I have a loop for create or update data like below
foreach ($goods_list as $goods) {
$w_estim_mp = WEstimMp::where('event_seq', \LoginInfo::event_data()['event_seq'])
->where('goods_seq', $goods['goods_seq'])
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
if (!isset($w_estim_mp)) {
$w_estim_mp = new WEstimMp;
$w_estim_mp->event_seq = \LoginInfo::event_data();
$w_estim_mp->goods_seq = $goods['goods_seq'];
$w_estim_mp->mp_item_category = $mp_item_category;
}
$w_estim_mp->num = $goods['num'];
$w_estim_mp->note = $goods['note'];
$w_estim_mp->proc_flg = 2;
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
$w_estim_mp->update_dtime = $now;
$w_estim_mp->save();
}
I don't know why i can update only last value of $goods_list.
Help me T.T Thank you!
You can use array_pop to remove the last element and array_push to insert a new element. Follow an example:
<?php
$initial_array = [1,2,3];
function change_last($array, $value) {
$removed_element = array_pop($array);
array_push($array, $value);
return $array;
}
$changed_array = change_last($initial_array, 4);
print_r($changed_array);
?>
and here a live example:
https://tech.io/snippet-widget/ZfEzgjj
I resolved my question!
I don't know why but i work, finnaly, after i changed to
foreach ($goods_list as $goods) {
$goods_seq = $goods['goods_seq'];
$num = $goods['num'];
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
->first();
if (!isset($goods['note'])) {
$goods['note'] = '';
}
$now = (new \Carbon\Carbon())->format('Y-m-d H:i:s');
if (!isset($w_estim)) {
$w_estim = new WEstimMp;
$w_estim->event_seq = $event_seq;
$w_estim->goods_seq = $goods_seq;
$w_estim->mp_item_category = $mp_item_category;
$w_estim->num = $num;
$w_estim->note = $goods['note'];
$w_estim->proc_flg = 2;
$w_estim->update_dtime = $now;
$w_estim->save();
} else {
$w_estim = WEstimMp::where('event_seq', $event_seq)
->where('goods_seq', $goods_seq)
// ->first()
->update([
'num' => $num,
'note' => $goods['note'],
'proc_flg' => 2,
'update_dtime' => $now,
]);
}
I have a trouble about phpmyadmin of laravel
I want to update the data from the view on the db via controller but I get an error occurred
// save all seats
foreach ($request->all() as $key => $param) {
if ($key === '_token') continue;
$data = explode('-', $key);
$bs = new BookedSeat();
$bs->booking_id = $booking->id;
$bs->day_id = str_replace('c', '', $data[0]);
$bs->table_id = str_replace('t', '', $data[1]);
$bs->number = 0;
$bs->status = 'requested';
$bs->save();
}
its an error when i try update data
its my db
Updated
// save all seats
foreach ($request->all() as $key => $param) {
if ($key === '_token') continue;
$data = explode('-', $key);
$bs = new BookedSeat();
$bs->booking_id = $booking->id;
$day = DB::table('days')->where('name',$data[0])->get();
$bs->day_id = $day->id;
$bs->table_id = str_replace('t', '', $data[1]);
$bs->number = 0;
$bs->status = 'requested';
$bs->save();
}
In layered navigation, when i select particular attribute, it gets disappeared from left side selection panel, so I want I should be able to select more than once.
If I come to know from what collection it is coming, that will be helpful.
-Thanks in Advance.
public function apply(Zend_Controller_Request_Abstract $request, $filterBlock) {
$filter = $request->getParam($this->_requestVar);
if (is_array($filter)) {
$text = array();
foreach ($filter as $f)
array_push ($text, $this->_getOptionText($f));
if ($filter && $text) {
$this->_getResource()->applyFilterToCollection($this, $filter);
$this->getLayer()->getState()->addFilter($this->_createItem($text, $filter));
$this->_items = array();
}
return $this;
}
$text = $this->_getOptionText($filter);
if ($filter && $text) {
$this->_getResource()->applyFilterToCollection($this, $filter);
$this->getLayer()->getState()->addFilter($this->_createItem($text, $filter));
$this->_items = array();
}
return $this;
}
public function applyFilterToCollection($filter, $value)
{
$collection = $filter->getLayer()->getProductCollection();
$attribute = $filter->getAttributeModel();
$connection = $this->_getReadAdapter();
$tableAlias = $attribute->getAttributeCode() . '_idx';
if (!is_array($value)) {
$conditions = array(
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
$connection->quoteInto("{$tableAlias}.value = ?", $value)
);
}else{
$conditions = array(
"{$tableAlias}.entity_id = e.entity_id",
$connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
$connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
$connection->quoteInto("{$tableAlias}.value in (?)",$value)
);
}
$collection->getSelect()->join(
array($tableAlias => $this->getMainTable()),
implode(' AND ', $conditions),
array()
);
//echo $collection->getSelect();
return $this;
}
I've done something similar, and you have to rewrite the Mage_Catalog_Model_Layer_Filter_Attribute class, which uses the method apply() to filter results.