bhartsfield
08/24/2022, 1:21 AMbhartsfield
08/24/2022, 1:26 AMcomponent table="dbo.tblUsers" extends="quick.models.BaseEntity" accessors="true" {
variables._key = "userId";
property name="userId";
property name="userName";
property name="active";
property name="countryId";
}
Countries.cfc
component table="dbo.Countries" extends="quick.models.BaseEntity" accessors="true" {
variables._key = "countryId";
property name="countryId";
property name="countryName";
property name="countryCode";
}
I'll always want the country info (not just the id) when I get a user.
I added the following to the users component and it gets the expected data back but it runs two individual queries instead of an inner join. So I am assuming I am just doing something wrong with the relationship.
country = () => belongsTo( "Countries", "CountryId" );
bhartsfield
08/24/2022, 1:29 AMgetInstance( "Users" ).with( "country" ).get()
sknowlton
08/24/2022, 1:31 AMfunction country() { return belongsTo( relationName = "Countries", foreignKey = "countryId" ); }
in this particular instance where you only have a couple fields, rather than doing an eager load and .with()
I'd use a subselect to just pull in countryName
and countryCode
scope withCountryData( qb ) {
qb.addSubselect( "countryName", "country.countryName" );
qb.addSubselect( "countryCode", "country.countryCode" );
}
this way you're only making one query (small savings) but you're not spinning up an entire CFC for each user (bigger savings)sknowlton
08/24/2022, 1:31 AMbhartsfield
08/24/2022, 1:34 AMbhartsfield
08/24/2022, 1:34 AMbhartsfield
08/24/2022, 2:07 AMwil-shiftinsert
08/24/2022, 7:39 AMwith().
The with()
construct is especially useful when you are loading multiple users. Let’s say you have 10 users from 3 countries, and you want to display oUser.getCountry.getName()
. Instead of firing 10 individual queries for each user’s country it is just firing two queries. One for all users and one for all related companies. So the benefits are not visible with just one user object. You can read about it here https://quick.ortusbooks.com/guide/relationships/eager-loading#with
I agree with Sam the subselects might be more efficient in some cases, especially if you need only one or just a few properties from the nested object.bhartsfield
08/24/2022, 10:47 AMwil-shiftinsert
08/24/2022, 10:52 AMbhartsfield
08/24/2022, 11:33 AMbhartsfield
08/24/2022, 11:34 AMbhartsfield
08/24/2022, 11:37 AMsknowlton
08/24/2022, 2:03 PM