Symfony 2 Self referencing many to many repository - mysql

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();

Related

convert query from mysql to php laravel?

My query is the following:
select employe.id, employe.nam, users.name, users.name_user
from employe
left join users
on users.name = employe.id
it is a query to two tables: employe, users.
How can I pass it to my controller? Am I new to laravel..
I assume the user to employee is a One to One relation.
Did you setup the relation in both models?
If so you can do the following in your controller:
$employees = Employee::with('user')->all();
This will load all employees and the related user.
Question is the users.name a foreign key on the employee.id?
Thats a bit strange, i recommend using id's on both models (autoIncrement).
Laravel use a MVC pattern, a good practice is use a Model for your employe table
I recomend you to use an Eloquen Model, so, your query will look like this:
Employe::select('employe.id', 'employe.nam', 'users.name', 'users.name_user')
->leftJoin('users', 'users.name', 'employes.id')
->get();
You can easily maintain this kind of query with Eloquent relationships.
Add this method on your employee model
public function user(){
return $this->hasOne('App\User','name','id');
}
Add this method on your user model
public function Employee(){
return $this->belongsTo('App\Employee','id','name');
}
Add line on your controller
$employees = Employee::with('user')->all();

Join two database table zend framework 1.12

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.

Django how to select foreign value in query

Having following models:
User(models.Model):
...
login = ...
Asset(models.Model):
user = models.ForeignKey(User)
...
How to select users login in Asset query using django QuerySet capabilities. For example:
Asset.objects.extra(select = {'user_login' : 'user__login'})
make to return query set with user_login field in each model object
Each Asset object already has a foreign key to the user. So you can always access -
asset = Asset.objects.get(pk=any_id)
if asset.user.login == 'some_value':
do_some_magic()
Please read the documentation.
Use .select_related('user') to select all assets and related users in a single query. Then simply access it through asset.user.login.
assets = Asset.objects.selec_related('user').filter(<any filter>)
for asset in assets:
# no additional queries here, as the user objects are preloaded into memory
print asset.user.login
I have found following solution:
Asset.object.extra( select = {'user_login' : '`%s.%s`' % (User._meta.db_table, 'login') } ).order_by('user__login')
The order_by expression is used to make JOIN on User's model table, than user's login can be accessed in SELECT expression within user_table.login

Updating a friend list in my database

I have been storing the friend list using the following database structure:
User Id | Friend Id
My problem is that I have an interface that lets them add/delete users from the friend list and the friend list should get saved upon hit.
So would it make sense that I delete all the friends for that user Id and then repopulate the database with the saved friend list ? Sounds a bit counterproductive because if a user adds just one more user, it would be deleting all the friends and re-adding them all.
You can delete all and then repopulate or you can store the initial state of the list of friends, then compare with the final list after user edit.
I recommend you use this function array_diff($array1, $array2), doing something like:
$initial_list = array (1,2,3,4,5);
$list_after_edit = array (1,2,5,6);
$all_new_items = array_diff($list_after_edit,$initial_list);
foreach ($all_new_items as $item) {
// Add to database this item
}
$all_deleted_items = array_diff($initial_list,$list_after_edit);
// Execute this query:
$query = 'DELETE FROM table WHERE `User Id` = <some ID> AND `Friend Id` in (' . implode(',',$all_deleted_items) . ')';

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.