I want a basic syntax of relation and their parameters
i need these clarification
Difference Between BELONGS_TO and HAS_ONE ?
I want to use the relation on CGridView (That relation refers the another table element as a Foreign key )
For Eg
I have Three tables
Messenger
UserLogin
Userprofile
I am in Messenger Admin Grid
I have Primary key of UserLogin table
That userlogin have userprofile Primary key
Now i want to access the userProfile fields in my grid
i already try the (through) in relation like
its in Messenger model
'relationeg'=>array(self::HAS_ONE,'Userprofile',array('user_id'=>'id'),'through'=>'user'),
'user'=>array(self::BELONGS_TO, 'UserLogin','user_id'),
i access this on my grid
.....
....
array(
'name'=>'message_by',
'value'=>'$data->relationeg->username'
),
....
...
But i got the wrong data's that are totally differ by the key of base table record
i have doubt on this line
'relationeg'=>array(self::HAS_ONE,'Userprofile',array('user_id'=>'id'),'through'=>'user'),
in this self::HAS_ONE means?
when i add the where condition of the join query how will add the condition on this
Advance thanks
Your answer welcome
KEY POINT : A BELONGS_TO relation says that a field in this model points to the primary key in another model; in this case, the current model owns the linking field.
KEY POINT : A HAS_ONE relation says that some other model has a linking field pointing to this model's primary key; in this case, the related model owns the linking field.
We can thik that a PARENT table will be the one that doesn't have a foreign key, and a CHILD table as the one who "depends" on the parent table, that is, it has a foreign key.
Given that, a CHILD BELONGS_TO a PARENT and a PARENT HAS_ONE CHILD.
The answer is here
Related
In Rails 4 models, I want to model an employee-department relationship. An employee belongs_to a department and a department has_many employees. Can I create a department_id reference in the employee table without making it a foreign key?
The reason I want to do this is that I suspect this impacts the record-locking behavior in MySQL, which is the database I am using, and it may be causing random errors when I perform concurrent updates from multiple threads in my Rails application.
Yes you can. If you're using Rails 4.2 and using references or add_reference within your migrations, just set the :foreign_key option to false.
You can also take the approach described by #user1063998 and just add an integer column called department_id to your employees table although in that case, I would recommend also adding an index for this column.
Rails by default does not add a foreign key constraint at the database level.
Using a migration you can simply add an integer column to the employee table called department_id. If you need to mimic the behaviour of a foreign key constraint, you can use validations on the model.
I want to make a one-to-many relationship like in the tutorial.
~~~
One To Many
An example of a one-to-many relation is a blog post that "has many" comments. We can model this relation like so:
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
}
~~~
So i want to make a Model Post (connected to table "posts") and a Model Comment (connected to table 'comments'). I am creating the tables in phpMyAdmin and not with migrations (because i have no SSH support on the online server). The comments table has a column 'posts_id'.
Can i use ...
$comments = Post::find(1)->comments;
..without defining a foreign key relationship between the two tables in phpmyadmin?
And if the answer is YES.
Should i make a column name "post_id" or something like this in my 'comments' table or something for this to work? Just like you would do with a normal foreign key?
You don't have to explicitly declare a foreign key in the MySQL side but you have at least to create a post_id column that will be used by Laravel as a foreign key.
Of course, you can name this column as you want and specify it in the declaration of the relation :
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment', 'post_primary_key');
}
}
You can also declare this column as a foreign key in PHPMyAdmin to improve robustness of your database but that's not Laravel business.
I am trying to use code first with an existing db. So far it went well, but now I am failing at a one to many to one relationship.
There is a table customer and a table address in the db where address does NOT have any customerid but a foreign one to many key FK_Address_Customer.
The auto created classes from the edmx look like
Customer:
public int CustomerID (PK)
public Address Address
Address:
public int AddressID (PK)
public HashSet<Customer> Customers
Whatever I do in the fluent API either fails with invalid column Address_AddressID or Multiplicity conflicts with the referential constraint error.
I assumed:
//Customer has one address, address can have multiple customers<br/>
pModelBuilder.Entity<Customer>().HasRequired(m => m.Address).WithMany(x => x.Customers);
//Address has multiple customers, customer has one address<br/>
pModelBuilder.Entity<Address>().HasMany(m => m.Customers).WithRequired();
I got this correct on other tables where there where NO foreign keys in the db by using HasForeignKey, but in the above scenario it does not work. I also tried via MapKey passing the foreign key name also with no luck.
Ho do I get this simple relationship going ?
Thanks
You must tell EF the name of FK in Customer table otherwise it will use default Address_AddressID. HasForeignKey will do the magic.
pModelBuilder.Entity<Customer>()
.HasRequired(c => c.Address)
.WithMany(a => a.Customers)
.HasForeignKey(c => c.AddressID);
Where AddressID is FK property in your Customer entity. If you don't have FK property in the Customer entity you need to use Map:
pModelBuilder.Entity<Customer>()
.HasRequired(c => c.Address)
.WithMany(a => a.Customers)
.Map(m => m.MapKey("AddressID"));
Where AddressID is a name of FK column in Customer table. You always need that column to have one-to-many relation.
The difference between having and not having FK property in your entity make difference between two types of associations supported by EF.
I have the below tables.
create table logical_id_seq (
logical_id int auto_increment,
primary key(logical_id)
);
create table mytable (
physical_id int auto_increment,
logical_id int not null references parent(logical_id),
data varchar(20),
primary key(physical_id)
);
The second table uses first table auto-generated value as its value. I am not sure how to model this in hibernate.
I read http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-onetoone, but I doesn't seem to understand.
It's actually hard to say, I don't know what you want to represent at the object level: is it a one-to-one foreign key association? a many-to-one association? is the association bi-directional? Using an ORM means thinking objects more than tables and it usually help to provide the object model.
I'll assume this is a one-to-one foreign key association. Here is what Java Persistence with Hibernate recommends:
7.1.2 One-to-one foreign key associations
Instead of sharing a primary key, two
rows can have a foreign key
relationship. One table has a foreign
key column that references the primary
key of the associated table. (The
source and target of this foreign key
constraint can even be the same table:
This is called a self-referencing
relationship.)
Let’s change the mapping from a User
to an Address. Instead of the shared
primary key, you now add a
SHIPPING_ADDRESS_ID column in the
USERS table:
<class name="User" table="USERS">
<many-to-one name="shippingAddress"
class="Address"
column="SHIPPING_ADDRESS_ID"
cascade="save-update"
unique="true"/>
</class>
The mapping element in XML for this
association is <many-to-one> — not
<one-to-one>, as you might have
expected. The reason is simple: You
don’t care what’s on the target side
of the association, so you can treat
it like a to-one association without
the many part. All you want is to
express “This entity has a property
that is a reference to an instance of
another entity” and use a foreign key
field to represent that relationship.
The database schema for this mapping
is shown in figure 7.3.
Figure 7.3 A one-to-one foreign
key association between USERS and
ADDRESS
An additional constraint enforces this
relationship as a real one to one. By
making the SHIPPING_ADDRESS_ID
column unique, you declare that a
particular address can be referenced
by at most one user, as a shipping
address. This isn’t as strong as the
guarantee from a shared primary key
association, which allows a particular
address to be referenced by at most
one user, period. With several foreign
key columns (let’s say you also have
unique HOME_ADDRESS_ID and
BILLING_ADDRESS_ID), you can
reference the same address target row
several times. But in any case, two
users can’t share the same address for
the same purpose.
Let’s make the association from User
to Address bidirectional.
Inverse property reference
The last foreign key association was
mapped from User to Address with
<many-to-one> and a unique
constraint to guarantee the desired
multiplicity. What mapping element can
you add on the Address side to make
this association bidirectional, so
that access from Address to User is
possible in the Java domain model?
In XML, you create a <one-to-one>
mapping with a property reference
attribute:
<one-to-one name="user"
class="User"
property-ref="shippingAddress"/>
You tell Hibernate that the user
property of the Address class is the
inverse of a property on the other
side of the association. You can now
call anAddress.getUser() to access
the user who’s shipping address you’ve
given. There is no additional column
or foreign key constraint; Hibernate
manages this pointer for you.
If what you have is actually a real many-to-one association, it should be pretty easy to adapt the above solution.
I have an application with three Models (Profile -> SubModel -> SubSubModel) chained together with has many relationships. I am trying to limit a user, after logging in, to only retrieving records that are associated with their Profile. I am very new to rails and this is what I had been trying in the Profile model
has_many :submodels, :conditions => {:profile_id => self.id}
but this is returning an empty data set when calling with Profile.find_by_id(1).submodels, how else could I achieve what I am trying to do. Or should I handle this in the controller or view instead, I thought it sounded well suited for the model to handle this.
you don't need any conditions on the has_many call - by default it will only return the SubModels associated with the Profile.
If you've named your classes and foreign/primary keys to Rails conventions, just use
class Profile
has_many :sub_models
end
and let Rails figure it out.
This assumes the following:
Profile wraps a table named profiles, which has a numeric primary key named id
SubModel wraps a table named sub_models, which has a numeric foreign key named profile_id