I'm trying to return a blog_post,blog_title from a MYSQL databse but I also need the user and his/her's data (in seperate array's)
The output should be like
array(
'blog1' => array(
'title' => 'this is a title',
'post' => 'This is the blogs content',
'user' => array(
'username' => 'Name',
'lastname' > 'Lastname'
)
),
'blog2' => array(
'title' => 'this is a title',
'post' => 'This is the blogs content',
'user' => array(
'username' => 'Name',
'lastname' > 'Lastname'
)
)
)
Using mysql there is no way of doing this in one query because it will mix up the two tables.
I have tried using left_join,right_join and selecting from multiple tables like
SELECT * FROM blogs a, users b WHERE b.id = a.id
Then I have tried using a foreach and a while loop.
$posts = array();
$x = 0;
while(++$x < 20){
$post = DB::query('SELECT * FROM posts WHERE id = '.$id.' ');
$post['user'] = DB::query('SELECT * FROM users WHERE id = '.$post['user_id'].' ');
$posts[] = $post;
}
But this will always return the same post/user
If you need a posts for a particular user it is possible to do like this (assumed you have a relation in posts table to users table by foreign key fk_user for each post):
$user_id = 1;
$posts = DB::query(
'SELECT posts.*,
users.username,
users.lastname
FROM posts
JOIN users ON users.id = posts.fk_user
WHERE user.id = '.$user_id
);
In case you need just a list of posts with related user info you can act as follows:
$posts = DB::query(
'SELECT posts.*, users.username, users.lastname
FROM posts
JOIN users ON users.id = posts.fk_user
LIMIT 100'
); // use your limit here
After you have a $posts array filled you can iterate and rearrange (if you need) or just use it as is:
foreach( $posts as $post ) {
// print post info here or rearrange array
$post['user'] = [
'username' => $post['username'],
'lastname' => $post['lastname'],
];
}
Related
I am trying to count the number of data in the database according to the category id and I have written the following lines of code:
public function getPodcastByCategoryId($catId){
$args = array(
'fields' => array(
'podcast.id',
'podcast.title',
'podcast.description',
'podcast.duration',
'podcast.audio',
'podcast.image',
'podcast.category',
'podcast.added_date',
'categories.title AS category_title',
'(SELECT users.full_name FROM users WHERE id = podcast.added_by) as author',
'(SELECT COUNT(category) FROM podcast WHERE category = podcast.category) as episodes'
),
'join' => "LEFT JOIN categories on podcast.category = categories.id",
'where' => array(
'category' => $catId
),
);
return $this->select($args);
}
However, the function getPodcastByCategoryId($catId) is giving episodes = 3 which is the count of data present in table podcast.
Data in database:
My expected episodes would be 2 in category id 2 and 1 in category id 1.
for episode you should use COUNT(*)
$args = array(
'fields' => array(
'podcast.id',
'podcast.title',
'podcast.description',
'podcast.duration',
'podcast.audio',
'podcast.image',
'podcast.category',
'podcast.added_date',
'categories.title AS category_title',
'(SELECT users.full_name FROM users WHERE id = podcast.added_by) as author',
'(SELECT COUNT(*) FROM podcast WHERE categories.category = podcast.category) as episodes'
),
'join' => "LEFT JOIN categories on podcast.category = categories.id",
'where' => array(
'category' => $catId
),
);
I make a custom search in WordPress. There are three fields for searching.
Age
Location
Post Title
Post Title is searched from wp_posts > post_title field and location and age are custom meta fields y_age, y_activity_locations. So there is 6 scenarios of searching.
If user enter:
Enter Title or
Select Location or
Select Age or
Enter Title and Select Location or
Enter Title and Select Age or
Select Location and Select Age
My first 5 (Five) scenarios are working perfectly but my 6th scenario is not working because it comes from same table (wp_postmeta) and same column but two different values.
So I tried this query:
Select y_posts.*, y_meta.*
From wp_posts As y_posts
Inner Join wp_postmeta As y_meta
On y_posts.ID = y_meta.post_id
Where y_posts.post_type = 'download'
And y_posts.post_status = 'publish'
And y_meta.meta_key = 'y_activity_locations'
And y_meta.meta_value Like '%Armidale%'
And y_meta.meta_key = 'y_age'
And y_meta.meta_value Like '%3 to 5%'
The query is not working because I think sever confused two values from same column.
Select y_posts.*, y_meta.*
From wp_posts As y_posts
Inner Join wp_postmeta As y_meta
On y_posts.ID = y_meta.post_id
Where y_posts.post_type = 'download'
And y_posts.post_status = 'publish'
And y_meta.meta_key = 'y_activity_locations'
And y_meta.meta_value Like '%Armidale%'
Or y_meta.meta_key = 'y_age'
Or y_meta.meta_value Like '%3 to 5%'
This query works and it gives me only age or location data but i want search both values at a same time.
I also tried sub query (Never tried before)
Select y_posts.*, y_meta.*
From wp_posts As y_posts
Inner Join wp_postmeta As y_meta
On y_posts.ID = y_meta.post_id
Where y_posts.post_type = 'download'
And y_posts.post_status = 'publish'
And y_meta.meta_key = 'y_activity_locations'
And y_meta.meta_value Like '%Armidale%'
And (Select yy_meta.* From wp_postmeta As yy_meta Where yy_meta.meta_key = 'y_age'
And yy_meta.meta_value Like '%3 to 5%')
But it gives me this error
1241 - Operand should contain 1 column(s)
So please guide me how can I get two values from same column.
Please give me only query suggestions not any other solutions.
Please try following query :
Select y_posts.*, y_meta.*
From wp_posts As y_posts
Inner Join wp_postmeta As y_meta
On y_posts.ID = y_meta.post_id
Where y_posts.post_type = 'download'
And y_posts.post_status = 'publish'
And (
(y_meta.meta_key = 'y_activity_locations'
And y_meta.meta_value Like '%Armidale%')
Or (y_meta.meta_key = 'y_age'
And y_meta.meta_value Like '%3 to 5%')
)
You try, wordpress query
<?php
$argsCat = array(
'posts_per_page' => -1,
'post_type' => 'download',
'meta_key' => 'y_activity_locations',
'meta_value' => '%Armidale%',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'y_age',
'value' => '3',
'compare' => '>='
),
'relation' => 'AND',
array(
'key' => 'y_age',
'value' => '5',
'compare' => '<='
)
),
);
$normal_array = get_posts($argsCat);
?>
Cakephp 2.6
I have a Model, Temps, which has many tickets. In the index view of Temps I want to return for each record, the ticket with the date closest to the current date.
In mySQL it can be done as
'SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() ORDER BY expiry_date ASC LIMIT 1'
But I don't know how to run this as a sub query. My Current query to generate my results is as follows: (bearing in mind this has been configured for datatables) Tickets is an alias for the Upload Model
public function getAjaxIndexData($data) {
$tokens = explode(" ", $data['searchString']);
$conditions = array(
$this->alias . '.deleted' => false,
'OR' => array(
'CONCAT(' . $this->alias . '.first_name," ",' . $this->alias . '.last_name) LIKE' => '%' . implode(' ', $tokens) . '%',
),
$data['columnsFilter']
);
$fields = array(
'id',
'full_name',
'pps_number',
'mobile',
'email',
'start_date',
'time_served'
);
$order = array(
$data['orderField'] => $data['order']
);
$contain = array(
'LocalOffice.name',
);
$options = array(
'conditions' => $conditions,
'fields' => $fields,
'order' => $order,
'contain' => $contain,
'limit' => $data['limit'],
'offset' => $data['start']
);
$optionsNoFields = array(
'conditions' => $conditions,
'contain' => $contain,
);
$result['draw'] = $data['draw'];
$result['recordsTotal'] = $recordTotal = $this->find('count');
$result['recordsFiltered'] = $this->find('count', $optionsNoFields);
$result['data'] = $this->find('all', $options); //standard search
$result['data'] = $this->formatTable($result['data']);
return json_encode($result);
}
Within this query I would like to add a field that shows the nearest expiry date for each Temp.
How would I construct this?
Dynamically create a virtual field:
$this->virtualFields['nearest'] = '(SELECT expiry_date FROM uploads WHERE expiry_date > CURDATE() AND uploads.owner_id = '.$this->alias.'.ticket_id ORDER BY expiry_date ASC LIMIT 1')';
Then adjust your fields array
$fields = array(
'id',
'full_name',
'pps_number',
'mobile',
'email',
'start_date',
'time_served',
'nearest'
);
Also, the query could be rewritten as ("temp" needs to be replaced with the model alias)
SELECT MIN(expiry_date)
FROM uploads
WHERE expiry_date > CURDATE()
AND uploads.owner_id = temp.ticket_id;
Which means that a potentially better performing query would be to move that subquery out of the columns of the SELECT statement to a JOIN. For example:
SELECT *
FROM temp
LEFT JOIN (SELECT MIN(expiry_date) AS expiry,owner_id
FROM uploads
WHERE expiry_date > CURDATE())
GROUP BY owner_id) AS next_dates
ON next_dates.owner_id = temp.ticket_id;
Learning php and I am losing my mind trying to solve this for days now. Please help.
This is a code which goes thought a table COUPON, take data with a condition met, and download it afterwards. In this table COUPON I have USER_ID as number but I want to have a user name also, which is kept in another table USER.
How can I go to another table (USER) and take names (REALNAME) by this USER_ID which is the same in both tables?
if ( $_POST ) {
$team_id = abs(intval($_POST['team_id']));
$consume = $_POST['consume'];
if (!$team_id || !$consume) die('-ERR ERR_NO_DATA');
$condition = array(
'team_id' => $team_id,
'consume' => $consume,
);
$coupons = DB::LimitQuery('coupon', array(
'condition' => $condition,
));
if (!$coupons) die('-ERR ERR_NO_DATA');
$team = Table::Fetch('team', $team_id);
$name = 'coupon_'.date('Ymd');
$kn = array(
'id' => 'ID',
'secret' => 'Password',
'date' => 'Valid',
'consume' => 'Status',
);
$consume = array(
'Y' => 'Used',
'N' => 'Unused',
);
$ecoupons = array();
foreach( $coupons AS $one ) {
$one['id'] = "#{$one['id']}";
$one['consume'] = $consume[$one['consume']];
$one['date'] = date('Y-m-d', $one['expire_time']);
$ecoupons[] = $one;
}
down_xls($ecoupons, $kn, $name);
After this, I want to try to do the same thing using only SQL queries.
You would need to JOIN the tables in the SQL query
SELECT something FROM coupons as coupons JOIN user as user ON coupons.id=user.id
You should use join when you want to retrieve details from two tables.
Join table COUPON and table USER based on user_id . This should yield results you want.
I'm trying to use Group by in find method for my relational database I want to get the latest record with unique receiver_id out of result set filtered by user_id and below is my code:
$this->loadModel('Chat');
$lastChat = $this->Chat->find('all', array(
'conditions' => array(
'Chat.user_id' => $user_id['User']['id']
),
'fields' => array(
'Chat.id',
'Chat.chat',
'Chat.user_id',
'Chat.receiver_id',
'Chat.read',
'Chat.created'
),
'group' => array('Chat.receiver_id'),
'order' => array('Chat.created DESC')
));
However, this does not seem to work. I'm not sure why but I'm only getting one result...
How can I get multiple results with rules based on above.
Try the following:
$db = $this->Chat->getDataSource();
$chats = $db->query("SELECT * , (Chat.user_id + Chat.receiver_id) AS dist
FROM (
SELECT *
FROM chats t
WHERE ( t.user_id =$id OR t.receiver_id =$id )
ORDER BY t.id DESC
) Chat
GROUP BY dist
ORDER BY Chat.id DESC");