Update Rows, column values represent as keys - mysql

Here's the overview of my table.
The thing is, the value of meta_key column represent as keys.
The problem is, how would I update the fields with user_id. For example, I want to update gender, employee_type, division, mobile that has a different values each field that has a user_id of 1.
I really have no idea how though, but on Eloquent there's this ->insert() to insert multiple values.
$meta_values = [
['user_id' => $user->id, 'meta_key' => 'mobile', 'meta_value' => $mobile,],
['user_id' => $user->id, 'meta_key' => 'address', 'meta_value' => $address,],
['user_id' => $user->id, 'meta_key' => 'gender', 'meta_value' => $gender],
['user_id' => $user->id, 'meta_key' => 'birthday', 'meta_value' => Carbon::parse($birthday)->format('Y-m-d')],
['user_id' => $user->id, 'meta_key' => 'employee_type', 'meta_value' => $employee_type],
['user_id' => $user->id, 'meta_key' => 'division', 'meta_value' => $division],
['user_id' => $user->id, 'meta_key' => 'date_employed', 'meta_value' => Carbon::parse($date_employed)->format('Y-m-d')],
['user_id' => $user->id, 'meta_key' => 'avatar', 'meta_value' => $images->avatar]
];
$user->userMeta()->insert($meta_values);
Here's the insert version, but how's the update version going to be or what it looks like. Any ideas?
I think it would be possible by using loop, but I probably think that it would not be a great idea.
--- EDITED ---
For now, here's my temporary solution. Here's what I'm gonna do in the first place but, until someone has an answer to this problem, this is my solution for now.
//List all fields in an array to be updated
$meta_array = ['mobile', 'address', 'gender', 'birthday', 'employee_type', 'division', 'date_employed'];
for ($i = 0; $i < count($meta_array); $i++) {
$user->userMeta()
->where('meta_key', $meta_array[$i])
->update(['meta_value' => ${$meta_array[$i]}]);
}

Something along this lines should work for you:
$meta_array = array('gender', 'employee_type', 'division', 'mobile');
Your\Model::where('user_id', 1)
->whereIn('meta_key', $meta_array)
->update(['meta_value' => 'some_new_value']);
The above PHP code should correspond to the following raw SQL query which you gave in your question as an example:
UPDATE your_table
SET meta_value='some_new_value'
WHERE user_id=1 AND meta_key IN ('gender', 'employee_type', 'division', 'mobile')

Related

How to get WooCommerce products from database based on multiple attributes

I want to get related products based on some criteria on product attributes like, the same sku, ean and gtin codes. But my query doesn't return any results. I tried different ways to query the database but all fail. Here is my query.
$sku = $product->get_sku();
$ean = $product->get_attribute( 'EAN' );
$gtin = $product->get_attribute( 'GTIN' );
$query = new WP_Query( array(
'post_type' => array('product'),
'posts_per_page' => 20,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_sku',
'value' => $sku,
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy' => 'pa_ean',
'field' => 'value',
'terms' => $ean,
'operator' => '=',
),
array(
'taxonomy' => 'pa_gtin',
'field' => 'value',
'terms' => $gtin,
'operator' => '=',
)
)
) );
By the way, if a product has ean code than it doesn't have a gtin and vice versa. It always has a sku which is unique to it self. But I have it added as a check to check if query at least returns value.
I can't find good documentary on this topic and hope someone here can help.

WordPress Order by using a meta_value not resulting in the correct order

There is a custom post type called guides and this has a meta post_views_count. The count is incremented each time someone visits a page of this post type. The data is being stored accurately.
Now I want to get a list of all posts ordered by the post_views_count so that I can see which article has been viewed the most.
Here is my query.
$query = new WP_Query( array(
'post_type' => 'guides',
'post_status' => 'publish',
'suppress_filters' => false,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'post_views_count',
'compare' => '>',
'value' => 0
)
),
'meta_key' => 'post_views_count',
'orderby' => 'meta_value post_date',
'order' => 'ASC',
) );
The problem is that meta_value in WordPress is stored as longtext, making it difficult to order a numeric value.
Any suggestions on how to get this working?
looks like it is sorting it as text, you will have to add 'meta_type' => 'NUMERIC', in your query so that meta_value is converted to number before sorting i guess. also try meta_value_num instead of meta_value in orderby
try
// Sort by numeric meta
'meta_key' => 'post_views_count',
'meta_type' => 'NUMERIC',
'order' => 'ASC',
'orderby' => 'meta_value_num',

Ordering by multiple ACF fields

I've seen a few questions similar to this but I still can't get things working so I thought I'd ask.
I have a Custom Post Type called 'Course'. This CPT has a custom field called 'date' which is either past, future or not set (null).
I am trying to write a query that hides the past courses, then shows future courses (ordered by date, soonest first) and then shows the courses where the date is not set (placeholder courses).
My plan was to add a 'placeholder_course' field to the course CPT and the date box would only appear if this was set to false. That way all of the placeholders would have a value of 1 for this field so I could sort by this to have them appear at then end, and then sort by the date to order the values in the date field correctly.
This is what I've been using:
<?php
$today = current_time('Ymd');
$args = array(
'post_type' => 'course',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
'placeholder' => array(
'key' => 'placeholder_course',
'compare' => '=',
'value' => '1
),
'future_dates' => array(
'key' => 'date',
'compare' => '>=',
'value' => $today,
)
),
'orderby' => array(
'placeholder' => 'ASC',
'future_dates' => 'ASC',
),
);
?>
but the ordering is still coming out muddled. I'm pretty sure I've just done something wrong in the query, can anyone shed any light please?
Set up a true/false field for your placeholder value (if no date is set you can check on it) then the following code runs through either future dates or any post with the placeholder true/false value set to true
UPDATE: your'e probably gonna have to do this with 2 queries.
$args = array(
'post_type' => 'course',
'posts_per_page' => -1,
'meta_key' => 'date',
'meta_query' => array(
array(
'key' => 'date',
'value' => $today,
'compare' => '>=',
),
),
'orderby'=> 'meta_value_num',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'course',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'placeholder_course',
'value' => true,
'compare' => '=',
),
),
'order' => 'ASC'
);

Fetch random row from group by query (mysql) in Cakephp

I have a table 'activities' and the columns are grouped by three of its attributes. Now I want to fetch Activity ID that is randomly selected from all the set of groups. The query is as follows:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
));
These are the things I tried and none of them worked.
1. Create a self join which should have random records
$this->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'Activity',
'order' => 'rand()',
'foreignKey' => 'id',
'fields' => 'Random.id'
)
)
));
This failed because the rand() order is appended in the end which simply randomizes all fetched activities.
Added a join option
'joins' => array(
array(
'table' => 'activities',
'alias' => 'Random',
'type' => 'LEFT',
'conditions' => array(
'Activity.id = Random.id'
),
'fields' => 'Random.id',
'order' => 'rand()'
)
This also didn't work as order value is not parsed by Cake
Tried to add condition
'Activity.id >= floor(rand() * (max(Activity.id) - min(Activity.id)) - min(Activity.id))'
Gave a mysql error
Please help me out
Assuming that your query is working:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
'order' => 'rand()',
'limit' => '1' // if you only want one random activity ID
));
Ok finally figured it out. We need to hack the way cake php works. In place of table name, I wrote a query to fetch randomly ordered records. Also notice the join type is 'right'. Left join wont produce randomly sorted list
$activities = $this->find('all', array('conditions' => $cond,
'page' => $page,
'limit' => $limit,
'fields' => array('count(*) as count, Random.id as id, max(Activity.modified) as Modified'),
'group' => $group,
'order' => 'Modified desc',
'joins' => array(
array(
'table' => '(select * from activities order by rand())',
'alias' => 'Random',
'type' => 'RIGHT',
'conditions' => array(
'Activity.id = Random.id'
),
)
)
));

How to search value from serialized data n mysql?

I want to search data which is stored in serialized form in this table.
Table Structure
For
meta_key - mgm_member_options
meta_value -
a:31:{s:2:"id";s:1:"1";s:13:"custom_fields";a:6:{s:10:"first_name";s:5:"Admin";s:9:"last_name";s:5:"Basil";s:7:"address";s:0:"";s:4:"city";s:0:"";s:5:"state";s:0:"";s:3:"zip";s:0:"";}s:22:"other_membership_types";a:0:{}s:12:"payment_info";a:0:{}s:6:"coupon";a:0:{}s:7:"upgrade";a:0:{}s:6:"extend";a:0:{}s:4:"code";s:10:"mgm_member";s:4:"name";s:10:"Member Lib";s:11:"description";s:10:"Member Lib";s:7:"setting";a:0:{}s:6:"saving";s:1:"1";s:8:"trial_on";s:1:"0";s:10:"trial_cost";s:1:"0";s:14:"trial_duration";s:1:"0";s:19:"trial_duration_type";s:1:"d";s:16:"trial_num_cycles";s:1:"0";s:8:"duration";s:1:"0";s:13:"duration_type";s:1:"m";s:6:"amount";s:1:"0";s:8:"currency";s:3:"USD";s:9:"join_date";s:0:"";s:13:"last_pay_date";s:0:"";s:11:"expire_date";s:0:"";s:15:"membership_type";s:5:"guest";s:6:"status";s:8:"Inactive";s:12:"payment_type";s:0:"";s:13:"autoresponder";s:0:"";s:10:"subscribed";s:0:"";s:9:"rss_token";s:32:"af8214c978dedcaa066bd8c223b7d22d";s:13:"user_password";s:16:"m9ROVxRwfxWwJzti";}
I want to find zip code.
How can do this using sql query?
Query that i am using
if(isset($_GET['as_zip']) && !empty($_GET['as_zip'])){
$as_zip = $_GET['as_zip'];
array_push($meta_query_array, array('key' => 'mgm_member_options', 'value' => $as_zip, 'compare' => '='));
} // prepare arguments $args = array( 'role' => $role, 'number' => '10', 'orderby' => 'display_name', 'fields' =>
'all_with_meta', 'meta_query' => $meta_query_array );