Join two database table zend framework 1.12 - mysql

I have used two mysql database in our projects. one database is connected the basic user information and another database used to store the daily activities. Now need to combine two database tables .
fetch user daily activity with user information , then need to join with master databases.
I found the solution in in PHP. But i want the solution on zend framework 1.12 ?
I used multidb functionality used to fetch different action .
resources.multidb.tb.adapter = "pdo_mysql"
resources.multidb.tb.host = "localhost"
resources.multidb.tb.username = "root"
resources.multidb.tb.password = ""
resources.multidb.tb.dbname = "#####"
resources.multidb.tb.default = true
resources.multidb.pl.adapter = "pdo_mysql"
resources.multidb.pl.host = "localhost"
resources.multidb.pl.username = "root"
resources.multidb.pl.password = ""
resources.multidb.pl.dbname = "#######"
But I want to query for join 2 tables in different databases.
example
SELECT db1.table1.somefield, db2.table1.somefield FROM db1.table1
INNER JOIN db2.table1 ON db1.table1.someid = db2.table1.someid WHERE
db1.table1.somefield = 'queryCrit';

Having in mind Zend's Join Inner declaration:
public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
And being '$this', for example, a Zend_Db_Table_Abstract implementation with adapter set to db1 (with _setAdapter()) and schema to "#####" (this is not really necessary because it'll use it as default):
$select = $this->select(true)->setIntegrityCheck(false)
->from(array('t1'=>'table1'),array('somefield')
->joinInner(array('t1b'=>'table1'),
't1.someid = t1b.someid',
array('t1b.somefield'),
'######')
->where('t1.somefield = ?', $queryCrit);
Please, note the the fourth parameter of the Inner Join method.
Hope this helps.

Related

How to write Db in Wordpress?

I have written a custom query to retrieve data in WordPress and it works fine in my local so when I move to the real environment its syntax will be like?
$dbconnect = mysqli_connect('localhost','root','','goldenstatecanna');
$query = mysqli_query($dbconnect,"SELECT *
FROM wp_terms JOIN wp_termmeta
WHERE wp_terms.term_id = wp_termmeta.term_id
and wp_termmeta.meta_key = \"display_type\"
and wp_termmeta.meta_value != \"subcategories\"");
Need to know how to write that with Wordpress Syntax
You can use the wpdb Class, this global WordPress class is key for using queries. In fact, every function uses this class.
$query = "SELECT COUNT(apple) FROM fruits";
$wpdb->query($query);
You can achieve this by this code
global $wpdb;
$querystr = "
SELECT *
FROM $wpdb->terms termss JOIN $wpdb->termmeta termssmeta
WHERE termss.term_id = termssmeta.term_id
AND termssmeta.meta_key = 'display_type'
AND termssmeta.meta_value != 'subcategories' ";
$dataa = $wpdb->get_results($querystr);
print_r($dataa);
You can also refer this https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
You should declare $wpdb as global before use it. It does work as an ORM for the Wordpress application, and there is a very extensive documentation about it, take a look, https://codex.wordpress.org/Class_Reference/wpdb

insert_from over two databases

I try to move all rows from one database table (source) to another database (target). The source-DB is a local database while target-DB runs on another machine. I want to transfer rows between the two databases and found the Model.insert_from() method for that task. Unfortunately it does nothing and I can't find any reason for that.
The database model is:
databaseSource = MySQLDatabase('sourceDB', **{'host': 'localhost', 'user': 'local', 'password': ''})
databaseTarget = MySQLDatabase('targetDB', **{'host': 'externalserver', 'user': 'external', 'password': ''})
class BaseModelSource(Model):
class Meta:
database = databaseSource
class BaseModelTarget(Model):
class Meta:
database = databaseTarget
class UsersSource(BaseModelSource):
crdate = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")])
description = TextField()
firstName = CharField(column_name='first_name')
class Meta:
table_name = 'users'
class UsersTarget(BaseModelTarget):
crdate = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")])
description = TextField()
firstName = CharField(column_name='first_name')
class Meta:
table_name = 'users'
With that my task should run with:
import peewee
from dbmodels import *
dataQuery = UsersSource.select(
UsersSource.crdate,
UsersSource.description,
UsersSource.firstName)
insertQuery = UsersTarget.insert_from(dataQuery,[
UsersTarget.crdate,
UsersTarget.description,
UsersTarget.firstName]).execute()
The resulting MySQL-query is this and as you can see, the selected data is empty []:
('INSERT INTO `users` (`crdate`, `description`, `first_name`) SELECT `t1`.`crdate`, `t1`.`description`, `t1`.`first_name` FROM `users` AS `t1`', [])
When I run the SELECT query on my table it outputs:
SELECT `t1`.`crdate`, `t1`.`description`, `t1`.`first_name` FROM `users` AS `t1`;
2018-08-12 16:50:36 valid Heinz
2018-08-12 19:34:45 valid Hilde
2018-08-12 19:33:31 invalid Paul
I searched like hell but didn't find any hint, why my result is empty.
Does anybody know more or a better method?
Peewee cannot insert data between two different database servers/connections. If both databases are on the same server, however, you can use the "schema" Meta option to reference each database from a single connection, and do the INSERT FROM that way:
db = MySQLDatabase('my_db')
class UsersSource(Model):
crdate = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")])
description = TextField()
firstName = CharField(column_name='first_name')
class Meta:
database = db
schema = 'source_db_name'
table_name = 'users'
class UsersTarget(Model):
crdate = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")])
description = TextField()
firstName = CharField(column_name='first_name')
class Meta:
database = db
schema = 'dest_db_name'
table_name = 'users'
If the databases are on different servers, then you have no other option but to dump it and reload it.
If this is a one-off operation I recommend using mysqldump and then copying the file to the remote server and sourcing the dumped files with the mysql client.
If this needs to be a continual process look at MySQL replication.
To batch transfer it you'll need to iterate over the result set of the SELECT and put this into the INSERT statement as they are on different servers.

Symfony 2 Self referencing many to many repository

I have a self referencing many to many relationship on my User entity being they can have many followers or follow many other users.
I am now trying to write a query in the user repository which will determine if a user is following another user.
I tried to write the query directy on user_relations (the mapping table) but it would not let me as it not related to the user entity.
So I tried:
$query = $this->createQueryBuilder('u')
->select('count(u.id)')
->innerJoin('u.following', 'r')
->where('u.id = :userID')
->where('r.from_id = :followingID')
->setParameter('userID', $userId)
->setParameter('followingID', $followingId)
Which results in an error stating the user entity does not have a field named from_uid.
How the hell can I correctly achieve this?
You can use MEMBER OF doctrine keyword
$query = $em->createQuery('SELECT u.id FROM User u WHERE :followingID MEMBER OF u.following');
$query->setParameter('followingID', $followingId);
$ids = $query->getResult();

How do I make a newsfeed without many join statements

What is the best way to approach making a newsfeed?
Currently I have an observer that creates a new newsfeedactivity record everytime someone creates a record. But, to deal with privacy I end up have 7 or 8 joins to get the appropriate output.
It seems like this is going to be slow and inefficient. What's another strategy for pulling out the right newsfeedactivity records as a scope?
More details:
Currently I have a site to help users track projects that they're working on. There are public and private projects (where people can invite collaborators).
I want my newsfeed to include when public projects are created. When you are invited to a private project. When a user follows a project. And then all of the actions of the other users that you're following. Then for the private projects I have another join table to determine who has access to the projects. (There are also comments on each of these projects that I want to show up in the newsfeed as well).
All of the following relationships are currently in join tables, which is why I have a lot of joins.
To get an idea of the type of query - I'm thinking it would look something like this:
SELECT news_feed_activities.* FROM news_feed_activities LEFT JOIN
user_following_relationships ON
user_following_relationships.following_id =
news_feed_activities.user_id LEFT JOIN
user_project_relationships ON
user_project_relationships.project_id =
news_feed_activities.responding_to_id AND
news_feed_activities.responding_to_type = 'Project' WHERE
(user_following_relationships.user_id = 1 OR
user_project_relationships.user_id = 1 OR
news_feed_activities.user_id = 1 OR
up2.user_id = 1) GROUP BY news_feed_activities.id ORDER BY
news_feed_activities.id DESC
EDIT:
I think I'm probably going to end up using Redis along these lines http://blog.waxman.me/how-to-build-a-fast-news-feed-in-redis
As RoR.
In your controller:
#user = current_user # (?)
recent_since = 24.hours.ago
#news_feed = []
# 1) I want my newsfeed to include when public projects are created.
#news_feed += Project.recent.open
# 2) When you are invited to a private project.
#news_feed += #user.invites.received.pending
# 3) When a user follows a project.
#news_feed += #user.user_following_relationships.recent
# 4) And then all of the actions of the other users that you're following.
#news_feed += #user.follows.collect(&:activities)
# 5) Then for the private projects I have another join table to determine who has access to the projects. (There are also comments on each of these projects that I want to show up in the newsfeed as well).
#news_feed += #user.projects.closed
#news_feed.sort!{ |a,b| a.created_at <=> b.created_at }
I did some sample scopes for you too.
project.rb
scope :recent, :conditions => ["created_at >= ?", 24.hours.ago]
scope :open, :conditions => "publicity = 'Public'"
scope :closed, :conditions => "publicity = 'Private'"
This is based on the precept that your news feed is actually a summary of recent activity across models rather than having a 'newsfeed' model.

Zend_Db using multiple databases?

Is there a way I can use Zend_Db to make updates and insert crossing multiple (two) databases?
Example,
UPDATE database1.tableA AS a1, databse2.tableA as a2 SET a1.content = a2.content WHERE a1.id = a2.id
How could I do this with Zend_Db_Adapter_Pdo_Mysql?
I have multiple databases defined in my application.ini file
I have used something like this:
// REGISTRY
Zend_Registry::set('configuration', $configuration);
foreach($configuration->database as $type => $database){
$db[$type] = Zend_Db::factory(
$database
);
}
Zend_Registry::set('db', $db);
Upon creating your model you specify which db you want in the models constructor
$newModel = Model_NewModel($db['db_key_name']);
You then have 3 options, you can either manually code your own object to extend Zend_Db_Table_Abstract and have a multi-db-update function
/* the code for this example is pseudo code, so it probably wont work but the concept is still good */
class Model_NewModel extends MoakCustomDbClass{
function multi_db_update($db1, $db2, $update, $where)
{
$originalDb = $this->_db;
$this->_db = $db1;
$this->update($update, $where);
$this->_db = $db2;
$this->update($update, $where);
$this->_db = $originalDb;
}
}
, write your own custom query by calling
$newModel->query('UPDATE QUERY');
or running 2 models both pointing at different databases
$newModelA = Model_NewModel($db['db_key_name_A']);
$newModelB = Model_NewModel($db['db_key_name_B']);