Yii2 ignore first database result - database

is there any way to ignore the first result record in Yii2 at a query? I have a list of numbers that represents a client. For designing purposes i had to query the first record separatly but now i have it duplicated. My questin is how can I query in Yii2 to ignore the first result?
Regards,
Gábor
The second find is the query where i need to ignore the first result:
public function actionGeneratePage() {
public function actionGeneratePage() {
$behivott = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(1)
->all();
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->all();
$reklam = Reklam::find()->all();
return $this->render('generatePage', [
'sorszamok' => $sorszamok,
'reklam' => $reklam,
'behivott' => $behivott,
]);
}

You use offset() to skip the first record:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(4)
->offset(1)
->all();
Also you can use a single query to get both $behivott and $sorszamok with array_shift:
$sorszamok = Sorszam::find()->with('ablak')
->orderBy(['behivas_datum' => SORT_DESC])
->limit(5)
->all();
$behivott = array_shift($sorszamok);

Related

Update records of database table : Laravel

I need to update the database table according to the edited data.
controller
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->update($request->all());
return back();
}
But nothing happens when I submit the form. When I use dd($request->all()); at the beginning of the function, it correctly shows the edited data as follows.
array:10 [▼
"_method" => "patch"
"_token" => "gOCL4dK6TfIgs75wV87RdHpFZkD7rBpaJBxJbLHF"
"editname" => "SUP_EVA_001"
"editdesc" => "des"
"editprice" => "1000.050"
"editlimit" => "1"
"editperunit" => "20.000"
"editexceedunit" => "30.000"
"productid" => "1"
"id" => "1"
]
But database has not been updated.
My table name is Table: subscription_plans and model is SubscriptionPlan
These are the table columns:
protected $fillable = [
'name',
'description',
'price',
'usage_limit',
'charge_per_unit',
'charge_per_unit_exceed',
'is_limit_exceed_considered',
'product_id'
];
Any idea on how to solve it or what I have done wrong?
If your solution did not work, try the 1by1 like this.
public function update(Request $request)
{
$subscriptionplan = SubscriptionPlan::find($request->id);
$subscriptionplan->_method = $request->_method;
$subscriptionplan->_token = $request->_token;
$subscriptionplan->editname = $request->editname;
$subscriptionplan->editdesc = $request->editdesc;
$subscriptionplan->editprice = $request->editprice;
$subscriptionplan->editlimit = $request->editlimit;
$subscriptionplan->editperunit = $request->editperunit;
$subscriptionplan->editexceedunit = $request->editexceedunit;
$subscriptionplan->productid = $request->productid;
$subscriptionplan->save();
return back();
}
In order for Laravel to automatically fill the model attributes, the indexes of the array passed to the fill method must correspond to your model attributes names.
Also, instead of
$subscriptionplan->update($request->all());
Use
$subscriptionplan->fill($request->all());
Then save the subscription plan with $subscriptionplan->save();

Drupal - Get custom taxonomy fields

I am trying to get a custom field assigned to taxonomy. I have tried this:
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
$terms is now storing all the terms from the vocabulary called 'zeme'. The problem is when I print this variable, it doesnt show the custom field that I need to get.
Any idea how can I get this custom field?
My code looks like this:
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
$term_data[] = array(
'id' => $term->tid,
'name' => $term->name
);
}
Here is the loadTree function official documentation :
TermStorage::loadTree
When you use the loadTree function, it will only get you the minimal datas to save execution time. You can see there is a $load_entities parameter set to false by default.
bool $load_entities: If TRUE, a full entity load will occur on the
term objects. Otherwise they are partial objects queried directly from
the {taxonomy_term_data} table to save execution time and memory
consumption when listing large numbers of terms. Defaults to FALSE.
So if you want to get all the datas of each of your taxonomy terms, you have to set $load_entities to true.
$vid = 'zeme';
$terms =\Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadTree($vid, 0, null, true);
Found this way from this post Get custom fields assigned to taxonomy:
$contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');
$terms = array();
foreach($contact_countries as $contact_countrie) {
$terms[] = array(
'contact_country' => $contact_countrie->name,
'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,
);
}
Very usefull!
public function getTaxonomyBuild(){
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('faq_sec');
foreach($terms as $term) {
$term_data[] = array(
'name' => $term->name,
'img' => file_create_url(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid)->get('field_sec_img')->entity->uri->value),
);
}
return $term_data;
}
good solution

Converting SQL Server query containing GROUP BY into NHibernate LINQ

I'm basically trying to retrieve a paged list of unique GUIDs, sorted by (row) creation date.
I've been able to draft a SQL Server query that seems to work for me based on this answer, but now I have to translate that into LINQ.
SELECT TOP 15 payment.ClientRef,
MAX(payment.CreatedDateUtc)
FROM PaymentTransactionState payment
INNER JOIN OrderState orderstate ON payment.ClientRef = orderstate.ClientRef
WHERE orderstate.UserId = 2 AND
payment.PaymentState IN (
'Rejected',
'Authorized')
GROUP BY payment.ClientRef
ORDER BY MAX(payment.CreatedDateUtc) DESC,
payment.ClientRef
Problem is, I can't apply GroupBy on an IQueryOver, I'm probably missing the appropiate syntax:
session
.QueryOver<Payment>()
.JoinAlias(orderState => orderState.OrderStateEntity, () => orderStateRow)
.Where(() => orderStateRow.UserId == customer.UserId)
.WhereRestrictionOn(payment => payment.PaymentState).IsIn(paymentStates)
.GroupBy(pts => pts.ClientRef)
.OrderBy(payment => payment.CreatedDateUtc).Desc
.Skip(pageIndex*pageSize)
.Take(pageSize)
.List();
I could probably do the group by in query syntax, but I'm not so sure about the Skip & Take bit.
I would try like this:
var query = db.PaymentTransactionState
.Where( pts => pts.OrderState.UserId == 2 &&
new string[] {"Rejected", "Authorized"}.Contains(pts.PaymentState) )
.GroupBy( pts => pts.ClientRef )
.OrderByDescending( pts => pts.Max( p => p.CreatedDateUtc))
.ThenBy( p => p.Key )
.Take(15);
So here's what worked for me: basically I had to use SelectList instead of GroupBy; SelectGroup, SelectMax & TransformUsing were easy to tackle once I found that;
PaymentRow paymentAlias = null;
OrderStateRow orderStateRow = null;
var transactionStateRows = session
.QueryOver<PaymentRow >()
.JoinAlias(orderState => orderState.OrderStateEntity, () => orderStateRow)
.Where(() => orderStateRow.UserId == customer.UserId)
.WhereRestrictionOn(payment => payment.PaymentState).IsIn(paymentStates)
.SelectList(list => list
.SelectGroup(payment => payment.ClientRef).WithAlias(() => paymentAlias.ClientRef)
.SelectMax(payment => payment.CreatedDateUtc).WithAlias(() => paymentAlias.CreatedDateUtc))
.TransformUsing(Transformers.AliasToBean<PaymentRow >())
.OrderBy(payment => payment.CreatedDateUtc).Desc
.Skip(pageIndex*pageSize)
.Take(pageSize)
.List();
I'll leave this here in case someone might find my travails useful in the future. Thank you for your replies.

Using array for MySQL Select Statement

Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get
Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )
What I am struggling with (and going around in circles) is a method to do the following..
Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.
concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].
I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.
Any help or pointers to relevant tutorials would be much appreciated
$codes = array();
foreach ($_POST as $key => $value) { // Loop through the $_POST array
if (preg_match('/^item_options_/', $key)) { // And validate the value
$item_arr = explode(' ', $value);
$item_id = $item_arr[1]; // Get the ID number from the value
if (is_numeric($item_id)) { // Validate it
$codes[] = $item_id; // Add it to the array we're building
}
}
}
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause
$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL

codeigniter update table row with new data array where

I have a database record with a uniqueID/PrimaryKe (OrderNumber)
I want to update the record with new data for that same PrimaryKey, OrderNumber.
My Controller is:
$data = array(
'CustomerName' => $this->input->post('customer'),
'CustomerAccountCode' => $this->input->post('accountcode'),
'PeriodStart' => substr($this->input->post('period'), 0,10),
'OrderUnitOfMeasure' => $this->input->post('buom'),
'CreditLimit' => $this->input->post('creditlimit'),
'BalanceBeforeOrder' => $this->input->post('currentbalance'),
'BalanceAfterOrder' => $this->input->post('newbalance'),
'OrderLines' => $this->input->post('orderlines'),
'TotalCost' => $this->input->post('grandtotal'),
'AverageDiscount' => $this->input->post('avediscount'),
'TotalCubes' => $this->input->post('grandtotalcubes'),
'TreatedCubes' => $this->input->post('grandtotaltreatedcubes'),
'SpecialComments' => $this->input->post('specialcomments'),
'CustomerReference' => $this->input->post('customerref'),
'ordernumber' => $this->input->post('ordernumber')
);
$this->sales_model->update_order_data($data);
My model is:
function update_order_data($q){
$this->db->where('CustomerOrderID', 'OrderNumber'); //ordernumber being post input ordernumber in array
$query = $this->db->update('Customer_Order_Summary');
}
So what I want is :
update 'Customer_Order_Summary'
set 'CustomerName'="$this->input->post('customer')",
set 'CustomerAccountCode'="$this->input->post('accountcode')",
//rest of set statements for each column and corresponding post
where 'CustomerOrderID'='OrderNumberInArray'//(post value)
This update statement is not working, any pointers would be appreciated.
Thanks as always,
Remove 'ordernumber' from your $data array and pass it separately
$this->sales_model->update_order_data($this->input->post('ordernumber'),$data);‌
The query should be like
function update_order_data($key,$q){
$this->db->where('CustomerOrderID', $key);
$query = $this->db->update('Customer_Order_Summary',$q);
}
Try:
function update_order_data($q)
{
$this->db->where('CustomerOrderID', $q['OrderNumber']);
$this->db->update('Customer_Order_Summary',$q);
return $this->db->affected_rows();
}
Note: Usually, in update functions, I have 2 arguments eg:
function update_something($pk,$data)
{
$this->db->where('primary_key', $pk);
$this->db->update('database_table',$data);
return $this->db->affected_rows();
}

Resources