Joining table data - mysql

I have a table of:
id title type expl bubble_content onfocus req dorder label mirror
1 Fullname 1 1 Your fullname Yes 0 0 0 NULL
Then another table of:
id fieldid relid dorder
4 1 2 0
5 1 1 0
How would I join the two tables so that the result would be something like:
0 => array(
'id' => 1,
'title' => 'Fullname',
.... etc ....
'relid' => 2,
'relid' => 1),
1 => array(
.... etc ....
))
I've tried using INNER JOIN / LEFT JOIN but this produces two rows/arrays for each relid, I would really like all the data for the particular fieldid to exist within the same array, as illustrated above.

You can't have 2 keys with the same name in an array. On your example you have 2 'relid', the second one will overwrite the first.
You can code PHP so that it merges those rows into one:
$output = array();
while ($row = mysql_fetch_assoc($result))
{
// Capture all values for this row first.
// If this is the new row from the first table, store.
if (!isset($output[$row['id']]))
{
$output[$row['id']] = $row;
// Make a new array for relids.
$output[$row['id']]['relids'] = array();
}
$output[$row['id']]['relids'][] = $row['relid'];
}
Your output array will look like this:
0 => array(
'id' => 1,
'title' => 'Fullname',
.... etc ....
'relids' => array(2, 1),
1 => array(
.... etc ....
))

Related

Cakephp3 multiple join table by Model

I have problem with my code. At this moment I have code view like this:
...Table.php
public function containBasic(){
return [
//Keywords
'CandidatesKeywords',
'CandidatesKeywords.Keywords',
//User
'CandidatesUser',
'CandidatesUser.User',
];
}
...Controller.php
$this->loadModel('Candidates');
$candidates = $this->Candidates->find()
->contain($this->Candidates->containBasic())
->where([
'CandidatesKeywords.Keywords.id'=>5
])
->all();
I include all other Models via contain. This method its works but when I try to search data in this code I have error like:
Unknown column 'CandidatesKeyword.id' in 'where clause
I don't know, how I can get column CandidatesKeywords -> Keywords -> Id from database :/
When I get (debug) all rows without where condition I get data like this:
'items' => [
(int) 0 => object(Cake\ORM\Entity) {
'id' => (int) 4,
.........
,
'candidates_user' => null,
'candidates_keyword' => object(App\Model\Entity\CandidatesKeyword) {
'id' => (int) 1,
..................
'keyword' => object(App\Model\Entity\Keyword) {
'id' => (int) 5,
.............
And I need to get rows with only keyword.id = 5.

foreignKey in model based on condition in cakephp

I am struck with one issue related to foreignKey concept.
I have two table users & user_relations.
users user_relations
id username id user_id friend_id status
1 abc 1 1 2 Accepted
2 def 2 2 3 Accepted
3 ghi 3 1 3 Accepted
here the friend_id is the foreign_key and my user_relations model looks like
public $belongsTo = array(
'Friend' => array(
'className' => 'User',
'foreignKey' => 'friend_id'
)
);
My conditions will be like
'conditions' => array(
"OR" => array(
'UserRelation.user_id' => $iLoggedUserId,
'UserRelation.friend_id' => $iLoggedUserId,
),
'ViewerRelationship.status' => 'Accepted'
)
Now when user "1" is logged in then he will get the info of users "2" & "3" based on foreignKey friend_id.
If user "2" gets logged in then, he is getting the info of users "2" & "3". But here I need to get the info of users "1" & "3". i.e., in one case it need to take the info based on the user_id not the friend_id
If I can keep the foreignKey in a condition I can get the result based on user_id or friend_id.
Any help please..!
I dont know how it is effective for you.
But it will solve your problem.
$respone = $this->UserRelation->find('all',
array('conditions'=> array(
'OR'=>array(
'UserRelation.user_id' => $iLoggedUserId,
'UserRelation.friend_id' => $iLoggedUserId
)
),
'fields' => array('UserRelation.*')
));
$reqFriendsId = array();
foreach($respone as $key => $val){
if($val['UserRelation']['friend_id'] == $iLoggedUserId){
array_push($reqFriendsId, $val['UserRelation']['user_id']);
}else{
array_push($reqFriendsId, $val['UserRelation']['friend_id']);
}
}
//For logged in user 1
Array
(
[0] => 2
[1] => 3
)
//For logged in user 2
Array
(
[0] => 1
[1] => 3
)

How to return mysql data using table aliases with left join and duplicate columns

I am trying to do a simple left join, while using table aliases, to return all of the values from both tables in this format:
[Alias1] => Array
(
[id] => 1
[city] => bay area
[state] => CA
)
[Alias2] => Array
(
[id] => 1
[city] => san francisco
[baseball_team] => giants
)
Here is my very simple mysqli_query:
$result = mysqli_query($sql, SELECT Alias1.id, Alias1.city, Alias1.state, Alias2.id, Alias2.city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id)
To get the results... I use:
while($row = mysqli_fetch_array($result))
{
$data[] = $row;
}
print_r($data);die();
Problem: The data prints out as such:
[0] => Array
(
[0] => 1
[id] => 1
[1] => bay area
[city] => bay area
[2] => CA
[state] => CA
[3] => 1
[4] => san francisco
[5] => giants
[baseball_team] => giants
)
Other Info: I originally tried to get the data using mysql_fetch_assoc($result)... But the duplicate columns don't return at all.
Instead of:
$data[] = $row;
Use this to form the data array that you desire:
$data['Alias1'] = array(
"id"=>$row['id'],
"city"=>$row['1_city'],
"state"=>$row['state'],
);
$data['Alias2'] = array(
"id"=>$row['id'],
"city"=>$row['2_city'],
"baseball_team"=>$row['baseball_team'],
);
OR, if you expect more than one row you need to use something like:
$data[] = array(
"Alias1" => array(
"id"=>$row['id'],
"city"=>$row['1_city'],
"state"=>$row['state'],
),
"Alias2" => array(
"id"=>$row['id'],
"city"=>$row['2_city'],
"baseball_team"=>$row['baseball_team'],
),
);
Note:
If your city values are different between your two tables then you should use an alias so that you can pull the other one differently. If they are the same, I suggest you not have them listed twice in the database as this is duplicating data and leaves your database denormalized.
Edit:
Your query should be something like
SELECT Alias1.id, Alias1.city AS 1_city, Alias1.state, Alias2.id, Alias2.city AS 2_city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id
See edited answers above for these aliases.

Create multi dimensional array in cakephp

Now I have 3 row of data.
id name date
1 data1 12-06-2013
2 data2 12-06-2013
3 data3 16-06-2013
now I want to group the 3 rows of data into a new array, something like:
Array
(
[2013-06-12] => Array
(
[0] => data1
[1] => data2
)
[2013-06-16] => Array
(
[0] => data3
)
)
the question is 1st i using foreach to show all date out.
<?php foreach($datax as $data):
echo $data['Model_Name']['id'];
endforeach;?>
then, while i looping i want to group up the $data sort to date as the multidimensional array as above.
Try below method,. you can add an additional column for date
$a = array(
array('datax' => array('id' => 1, 'name' => 'data1')),
array('datax' => array('id' => 2, 'name' => 'data2')),
array('datax' => array('id' => 3, 'name' => 'data3'))
);
$result = Set::classicExtract($a, '{n}.datax.id');
/* $result now looks like:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
$result = Set::classicExtract($a, '{n}.datax.name');
/* $result now looks like:
Array
(
[0] => data1
[1] => data2
[2] => data3
)
*/

WordPress get specific posts in arbitrary order

Right now, I'm doing:
$posts = get_posts(array('post_type' => 'page', 'post__in' => array(1, 3, 2, 9, 7)));
and am having two issues:
Post 3 is of 'post_type' => 'post', so it doesn't get selected, but I want it! If I leave out 'post_type' => 'page', then only post 3 is selected (because it must assume 'post_type' => 'post'.).
I want to be able to order the posts arbitrarily by their ids. If I knew how to use MySQL, I could do:
SELECT * FROM wp_posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7');
But, how should I do this with WordPress?
First fetch all posts arbitrarily by their ids and then loop through all the posts
You can do in this way:-
$posts=$wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7')");
$count=count($posts);
for ($counter=0 ; $counter < $count; $counter++)
{
$post=get_post( $posts[$counter]->ID, $output );
//do your stuffs with posts
}
Hope this helps
Kawauso on the #wordpress IRC channel informed me that "post_type takes an array of values." From that, I found that the following also selects post 3:
So, I did the following:
$post_ids = array(1 => 0, 3 => 1, 2 => 2, 9 => 3, 7 => 4);
$posts = get_posts(array('post_type' => array('post', 'page'),
'post__in' => array_keys($post_ids)));
$ordered_posts = array(0,0,0,0,0); // size of five; keeps order
foreach ($posts as $p) {
setup_postdata($p);
$ordered_posts[$post_ids[$p->ID]] = array(
'permalink' => get_permalink($p->ID),
'title' => $p->post_title,
'excerpt' => get_the_excerpt(),
'date' => date('F j, Y', strtotime($p->post_date)));
}
According to this thread, you can use this code and then use the classic WordPress loop:
$args = array(
'post_type'=>'page',
'orderby'=>'menu_order',
'order'=>'ASC'
);
query_posts($args);