Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find a model's relationships?

Tags:

I want to, when given a particular model, return all the related models it is associated with. For example:

class Dog < ActiveRecord::Base   has_many :bones   belongs_to :master end  d = Dog.first d.associations #<== should return [Bone, Master] 

Is there a way to do this already without having to roll my own? Failing that, any suggestions for the best way to do this?

like image 906
PJ. Avatar asked Nov 03 '08 18:11

PJ.


People also ask

What is relationship Modelling?

EDUQAS. WJEC. All Exam Boards. Entity relationship modelling is a top-down technique that is used to visualise and help understand the entities and the relationships between them. A data model — presented in the form of an entity relationship diagram — is one of the first steps of database design.

What is model relation in Laravel?

One to one relationship For example, every user is associated with a single post or maybe multiple posts, but in this relationship, we will retrieve the single post of a user. To define a relationship, we need first to define the post() method in User model.

What is a one-to-many relationship?

In a relational database, a one-to-many relationship exists when one row in table A may be linked with many rows in table B, but one row in table B is linked to only one row in table A. It is important to note that a one-to-many relationship is not a property of the data, but rather of the relationship itself.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.


1 Answers

Dog.reflect_on_all_associations 

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#M001405

You wouldn't do this on an instance but on the model itself.

like image 151
Matt Rogish Avatar answered Sep 18 '22 01:09

Matt Rogish