Fetching records from Many to Many relationship does not work as expected in Phalcon - many-to-many

I have created the phalcon models and relationship as per they provided the document but getting the error "Notice: Undefined property: Phalcon\Mvc\Model\Resultset\Simple::$GroupsMembers in /var/www/html/uno/apps/webservice/controllers/UserController.php on line 245" while trying to fetch related records in many to many relationship.
I have 3 tables users, groups and group_members. group_members contain the relationship for groups and users.I want to get the all subscribed groups for a member therefore I have used below statements in UserController:
$user = Users::find('id = '.$user_id);
$subscribed_groups = $user->groupsMembers;
foreach($groupMembers as $groupMember){
echo $groupMember->groups->title;
}
It gives the error mentioned above.
Please visit the link below to see my tables, models and controller.
http://forum.phalconphp.com/discussion/5928/fetching-records-from-many-to-many-relationship-does-not-work-as-expected-in-phalcon
Thanks.

Thank you Calin Rada (http://forum.phalconphp.com/user/283/calinrada) for answer.
Correct answer is:
find() method is returning an instance of Phalcon\Mvc\Model\Resultset\Simple but findFirst() will return an instance of your object (User in your case).
Detail answer on:
http://forum.phalconphp.com/discussion/5928/fetching-records-from-many-to-many-relationship-does-not-work-as

You use the alias GroupsMembers but then refer to it as $user->groupsMembers which is causing the undefined property notice.
Adjust your code to
$subscribed_groups = $user->GroupsMembers;
And it should work.

Related

relationships with multiple level eloquent [duplicate]

I know this question has been asked but my situation is different.
I have Post model with relationship to Comment model defined:
/*Post Model*/
public function comments(){
return $this->hasMany('comment');
}
and Comment model which each comment belong to one user :
/comment model/
public function user(){
return $this->belongto('user');
}
now I want to query all post and eager load comments (of each post) along with user information who post the comment.
anyway to make it work please ?
thank you.
What you want is nested eager loading, scroll down a bit and you will see it.
Quoting the docs:
To eager load nested relationships, you may use "dot" syntax. For
example, let's eager load all of the book's authors and all of the
author's personal contacts in one Eloquent statement:
$books = Book::with('author.contacts')->get();
In your case
$posts = Post::with('comments.user')->get();

How to limit results in reverse relation in Django

I have two tables, one called Company and the other called User, each user is related to one company using ForeignKey. So I can use reverse relation in Django to get all users for specific company (e.g. company.users)
In my case, I'm building ListAPIView which return multiple companies, and I'd like to return latest created user. My problem is that I don't want to use prefetch_related or select_related so it will load all the users, as we might end up having thousands of users per each company! Also I don't want to load each latest user in a separate query so we end up having tens of queries per API request!
I've tried something like this:
users_qs = models.User.objects.filter(active=True).order_by('-created')
company_qs = models.Company.objects.prefetch_related(
Prefetch('users', queryset=users_qs[:1], to_attr='user')
).order_by('-created')
In this case, prefetch_related failed as we can't set limit on the Prefetch's queryset filter (it gives this error "Cannot filter a query once a slice has been taken.")
Any ideas?
I think you are providing an object instead of a queryset Prefetch('users', queryset=users_qs[:1], to_attr='user')

Eloquent/Query Builder for more complicated table structures

OK so this probably isn't the biggest problem in the world and I'm sure someone will be able to help me out with where I'm going wrong. Here's a few facts before I get to my problem:
Laravel 5 & mysql
I have 3 main tables: meetups, events and locations
I also one pivot table: event_location
Meetups hasMany Events
Events belongsTo Meetups
Events belongsToMany Locations
Locations belongsToMany Events
The problem
I'm currently trying to search the locations (via a form – i.e. Input::get('data')), and this would bring up all events that have that location, and all meetups that associate with that event.
Within my SearchController, I have the following:
// Get the searched data
$data = Input::get('data');
// Get all location, which are 'LIKE' the inputted data.
$locations = Location::where('title', 'LIKE', '%'. $data .'%')->get();
At this point I'm not sure how to proceed. I need to access the events from each location and after that I'd need a get the meetup that corresponds with that location, but I'm not sure how to go about this. Can this be done with joins() or would I loop through the $locations variable and get the ->events for each of those and put them into an array? Or, should I be using DB:: and running a custom query?
See #iavery's comment, it seems the following works when you have all belongsToMany relationships:
Location::where( ... )->with('events.meetups')->get();

cakephp retrive data from one table excluding the associated tables

I am struggling with a basic problem. i am using cake php 2.5. i try to apply the find query in the company model and receiving all the data from companies and with its associations, but i only want to receive the data from company table and want to exclude the data from rest of relationships, can anyone help me with this. below are my queries.
$this->loadModel('Company');
$fields=array('id','name','logo','status');
$conditions=array('status'=>1);
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
print_r($search_companies);die();
echo json_encode($search_companies);die();
With out seeing your data output, I am just going to take a stab at the problem.
Inside your $search_companies variable you are getting a multidimensional array probably with the other values of the other tables.
Why not just select the one array:
$wantedData = $search_companies['Company'];
// The key Company (which is the model) should be the data you are wanting.
Try setting model's recursive value to -1
$this->Company->recursive = -1;
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
With this you will not fire the joins queries and therefore you only retrieve model's information.
Cakephp provide this functionality that we can unblind few/all associations on a any model. the keyword unbindModel is used for this purpose. inside the unblindModel you can define the association type and model(s) name that you want to unblind for that specific association.
$this->CurrentModelName->unbindModel(array('AssociationName' => array('ModelName_Youwwant_unblind')));

sqlalchemy relations and query on relations

Suppose I have 3 tables in sqlalchemy. Users, Roles and UserRoles defined in declarative way. How would one suggest on doing something like this:
user = Users.query.get(1) # get user with id = 1
user_roles = user.roles.query.limit(10).all()
Currently, if I want to get the user roles I have to query any of the 3 tables and perform the joins in order to get the expected results. Calling directly user.roles brings a list of items that I cannot filter or limit so it's not very helpful. Joining things is not very helpful either since I'm trying to make a rest interface with requests such as:
localhost/users/1/roles so just by that query I need to be able to do Users.query.get(1).roles.limit(10) etc etc which really should 'smart up' my rest interface without too much bloated code and if conditionals and without having to know which table to join on what. Users model already has the roles as a relationship property so why can't I simply query on a relationship property like I do with normal models?
Simply use Dynamic Relationship Loaders. Code below verbatim from the documentation linked to above:
class User(Base):
__tablename__ = 'user'
posts = relationship(Post, lazy="dynamic")
jack = session.query(User).get(id)
# filter Jack's blog posts
posts = jack.posts.filter(Post.headline=='this is a post')
# apply array slices
posts = jack.posts[5:20]