Having a lot of trouble with Yii2 QueryBuilder - model-view-controller

public function getOrderItemStatus($magentoorderitemid) {
$query = (new \yii\db\Query())
->select(["COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier", "COALESCE(ShipTracking.ShipVendor, '') AS ShipMethod", "COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier","COALESCE(ShipTracking.TrackingNumber, '') AS TrackingNumber"])
->from('OrderDetails')
->leftJoin('PickTicketOrders','PickTicketOrders.OrderId = OrderDetails.OrderId')
->leftJoin('ShipTracking', 'ShipTracking.PickTicketId = PickTicketOrders.Id')
->leftJoin('Products', 'Products.ISBN = OrderDetails.ISBN')
->where('OrderDetails.MagentoOrderItemId=:magentoorderitemid', [':magentoorderitemid' => $magentoorderitemid]);
$result = Yii::$app->db->createCommand($query)->execute();
return $result;
}
Even when I remove the joins and the where, and I change the select to *. It doesn't work

$query = (new \yii\db\Query())
->select(["COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier", "COALESCE(ShipTracking.ShipVendor, '') AS ShipMethod", "COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier","COALESCE(ShipTracking.TrackingNumber, '') AS TrackingNumber"])
->from('OrderDetails')
->leftJoin('PickTicketOrders','PickTicketOrders.OrderId = OrderDetails.OrderId')
->leftJoin('ShipTracking', 'ShipTracking.PickTicketId = PickTicketOrders.Id')
->leftJoin('Products', 'Products.ISBN = OrderDetails.ISBN')
->where('OrderDetails.MagentoOrderItemId=:magentoorderitemid', [':magentoorderitemid' => $magentoorderitemid]);
$command = $query->createCommand();
$result = $command->queryAll();
Use this query in this way

I ended up using the following and it works
$query = (new \yii\db\Query())
->select(["COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier", "COALESCE(ShipTracking.ShipVendor, '') AS ShipMethod", "COALESCE(ShipTracking.ShipCarrier, '') AS ShipCarrier","COALESCE(ShipTracking.TrackingNumber, '') AS TrackingNumber"])
->from('OrderDetails')
->leftJoin('PickTicketOrders','PickTicketOrders.OrderId = OrderDetails.OrderId')
->leftJoin('ShipTracking', 'ShipTracking.PickTicketId = PickTicketOrders.Id')
->leftJoin('Products', 'Products.ISBN = OrderDetails.ISBN')
->where('OrderDetails.MagentoOrderItemId=:magentoorderitemid', [':magentoorderitemid' => $magentoorderitemid]);
$result = $query->all();

Related

For loop request Laravel

Just a quick question guys really thankful for everyone who can help.
How do I foreach loop inside create eloquent in laravel
Here is my code. I'm trying to get and match the answers for their respective survey questions
public function answer_survey(Request $request, $id)
{
$userId = Auth::user()->id;
$user = User::where('id', $userId)->first();
$userNectarPoint = UserNectarPoint::where('user_id', $userId)->first();
$survey = Survey::find($id);
$survey_questions = SurveyQuestion::where('survey_id', $survey->id)->get();
$current_nectarpt_value = $userNectarPoint->nectar_points;
$questionIds = $request->id;
$questions = $request->question;
$answers = $request->answer;
foreach ($answers as $answer) {
}
foreach ($survey_questions as $survey_question) {
$userAnsweredSurvey = new UserAnsweredSurvey;
$userAnsweredSurvey->user_id = $userId;
$userAnsweredSurvey->user_fullname = $user->first_name . ' ' . $user->middle_initial . ' ' . $user->family_name;
$userAnsweredSurvey->survey_id = $survey->id;
$userAnsweredSurvey->survey_title = $survey->title;
$userAnsweredSurvey->survey_question_id = $survey_question->id;
$userAnsweredSurvey->survey_question = $survey_question->question;
$userAnsweredSurvey->answer = $answer;
$userAnsweredSurvey->save();
}
$result_nectarpt = $current_nectarpt_value + $survey->reward_points;
$userNectarPoint->nectar_points = $result_nectarpt;
$userNectarPoint->save();
return back()->with('status', 'survey_done');
}

Laravel query in if cause

I run the below query, if cause true then where cause is apply like below, but when i run below query it gives me "Out of memory (allocated 503316480) (tried to allocate 492834816 bytes)" error, So another easy way to check the where cause above if condition.
Here below is my code.
$user_id = "";
$doctor_id = "";
$start_date = "";
$end_date = "";
if(isset($request->user_id)) {
$user_id = $request->user_id;
}
if(isset($request->doctor_id)) {
$doctor_id = $request->doctor_id;
}
if(isset($request->start_date)) {
$start_date = $request->start_date;
}
if(isset($request->end_date)) {
$end_date = $request->end_date;
}
$query = DB::table('request_approves')
->join('city_masters', 'request_approves.city_id', '=', 'city_masters.id')
->join('doctors', 'request_approves.doctor_id', '=', 'doctors.id')
->select('doctors.*','city_masters.*','request_approves.*');
if($user_id !== "") {
$query->where('request_approves.user_id', 2);
}
if($doctor_id !== "") {
$query->where('request_approves.doctor_id',3);
}
if($start_date !== "" & $end_date !==""){
$query->whereBetween('request_approves.approve_time', array($start_date,$end_date));
}
$query->get();
Not sure what it is happening, but your code seems wrong to me .
On the if statements you do something like this $query->where('request_approves.user_id', 2); but where this returned values go ? To continue the same query you should do it like this:
$query = DB::table('request_approves')
->join('city_masters', 'request_approves.city_id', '=', 'city_masters.id')
->join('doctors', 'request_approves.doctor_id', '=', 'doctors.id')
->select('doctors.*','city_masters.*','request_approves.*');
if($user_id !== "") {
$query = $query->where('request_approves.user_id', 2);
}
if($doctor_id !== "") {
$query = $query->where('request_approves.doctor_id',3);
}
if($start_date !== "" & $end_date !==""){
$query = $query->whereBetween('request_approves.approve_time', array($start_date,$end_date));
}
$query = $query->get();
PHP uses memory to perform queries as well. So performing queries from a PHP application will indeed use more memory than performing them straight from MySQL.
I did a simple calculation and 503316480 bytes comes out to 503MB. So I would suggest modifying your php.ini settings. This should let you output data, and from there you can tune your SQL.
In your php.ini
memory_limit=503M

Laravel Operators AND / && - How to Use Them?

I am trying to use AND as well as && in this code block:
public function show($id)
{
$user = Auth::user()->id;
$userEmail = Auth::user()->email;
$share = Share::where('sbj_id', $id)->first();
if ($share->sbj_id == $id && $share->email == $userEmail ) {
$items = Item::where('project_id', $id)
->orderBy("created_at", "desc")
->groupBy('label_name')
->get();
$sbj = Sbj::find($id);
$allSbj = Sbj::where('user_id', $user)->orderBy("created_at", "desc")->get();
$labels = Label::all();
$pages = Page::where('project_id', $id)->orderBy('created_at', 'desc')->get();
$people = Friend::where('sbj_id', $id)->orderBy("created_at", "desc")->get();
$myPeeps = Contact::where('my_id', $user)->get();
return View::make('sbjs.show', compact('sbj', 'pages', 'labels', 'people', 'myPeeps', 'allSbj', 'items'));
} else {
return Redirect::action ('SbjsController#index');
}
}
However, I am looking online to see if && or AND is supported in Lavavel in this context but no success. My app is taking the user to the ELSE action.
Any ideas?
I just added the Eloquent statement to the IF conditional and it worked fine...not sure why it was not evaluating.

How to get parameters in JFormField from a disabled plugin in Joomla 1.6/2.5?

How i can get some parameters from a disabled/not yet actived plugin in joomla 1.6/2.5?
$module = JPluginHelper::getPlugin('system','myplugin');
$moduleParams = new JParameter($module->params);
$val = $moduleParams->get("key");
This method didn't work becouse i need to use within an element JFormField generator.
Thanks for help!
With JPluginHelper::getPlugin it's possible to access only enabled plugins, so here's the code for direct access to database.
// Build query
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select( 'params' )
->from( '#__extensions' )
->where( 'type = ' . $db->q('plugin') )
->where( 'folder = ' . $db->q('authentication') ) // Plugin type
->where( 'element = ' . $db->q('gmail') ) // Plugin element
;
// Execute query
$db->setQuery($query);
try
{
$result = $db->loadResult();
}
catch (RuntimeException $e)
{
return false;
}
// Parse parameters
if (!empty($result))
{
$params = new JRegistry($result);
$val = $params->get('key', 'defaultValue');
}
You may store query results in in the JFormField Object so save database queries in case field is availabile multiple times.
protected $results = null;
Perhaps you may want to try this:
// Get plugin parameters
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('`params`')
->from ('`#__extensions`')
->where ("`type` = 'plugin'")
->where ("`folder` = 'system'")
->where ("`element` = 'myplugin'");
$db->setQuery($query);
$res = json_decode($db->loadResult(), true);
$val = $res['key'];
Just find the answer by myself.
$data = null;
foreach ((array) $this->form as $k => $v) {
if($val instanceof JRegistry){
$data = &$v;
break;
}
}
$data = $data->toArray();
$val = $data['params']['key'];
Thanks! Bye!

Magento: improving default search engine

So, I changed the default Magento search engine slightly, and it works close to how I want it. (i.e. OR term search to AND). However, there is one more thing that I'd like to implement. When a person searches for a series of terms, like Green Apple A, I'd like the product Green Apple A to show up first. Right now, with the AND operator, the results are in the order they were pulled from the DB. So, the Green Apple A might show up in anywhere.
Here is the function that prepares the results.. It is a bit complicated for me, and I'm wondering if there's an easy way to "append" a search result that looks for the specific sequence of the inputted terms and concatenates the results, giving this priority, so it shows up first.
(Sorry for the long code. I typically don't like posting large amount of code)
From Fulltext.php in /stores/my_website/app/code/local/Mage/CatalogSearch/Model/Resource
public function prepareResult($object, $queryText, $query)
{
$adapter = $this->_getWriteAdapter();
if (!$query->getIsProcessed()) {
$searchType = $object->getSearchType($query->getStoreId());
$preparedTerms = Mage::getResourceHelper('catalogsearch')
->prepareTerms($queryText, $query->getMaxQueryWords());
$bind = array();
$like = array();
$likeCond = '';
if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE
|| $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
) {
$helper = Mage::getResourceHelper('core');
$words = Mage::helper('core/string')->splitWords($queryText, true, $query->getMaxQueryWords());
foreach ($words as $word) {
$like[] = $helper->getCILike('s.data_index', $word, array('position' => 'any'));
}
if ($like) {
$likeCond = '(' . join(' AND ', $like) . ')';
}
}
$mainTableAlias = 's';
$fields = array(
'query_id' => new Zend_Db_Expr($query->getId()),
'product_id',
);
$select = $adapter->select()
->from(array($mainTableAlias => $this->getMainTable()), $fields)
->joinInner(array('e' => $this->getTable('catalog/product')),
'e.entity_id = s.product_id',
array())
->where($mainTableAlias.'.store_id = ?', (int)$query->getStoreId());
if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT
|| $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE
) {
$bind[':query'] = implode(' ', $preparedTerms[0]);
$where = Mage::getResourceHelper('catalogsearch')
->chooseFulltext($this->getMainTable(), $mainTableAlias, $select);
}
if ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
$where .= ($where ? ' AND ' : '') . $likeCond;
} elseif ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE) {
$select->columns(array('relevance' => new Zend_Db_Expr(0)));
$where = $likeCond;
}
if ($where != '') {
$select->where($where);
}
$sql = $adapter->insertFromSelect($select,
$this->getTable('catalogsearch/result'),
array(),
Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE);
$adapter->query($sql, $bind);
$query->setIsProcessed(1);
}
return $this;
}
I think you can try this free extension for default search
http://www.magentocommerce.com/magento-connect/catalog/product/view/id/12202/s/enhanced-default-search-9697

Resources