How to join two tables in cakephp 3.x with a custom fieldname? - join

I have one table called countries which has a field i.e ID with primary key and the other table is customers which has a field called primary_country. I want to join both the tables in cakephp way, but always it is taking customers.country_id which is not present in the table. I am using primary_country because the table also has alternate_country field. so i can't use country_id. Please provide me any solution so that I can fetch the country names on the basis of primary_country and alternate_country.

You'll need to modify your table object with the foreign key, as mentionned here:
https://book.cakephp.org/3.0/en/orm/associations.html
It could be something like that, in your case :
class CustomersTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Countries')
->setForeignKey('primary_country');
}
}
But i must say that if your model is still under conception, you may want to make an third table customer_countries and make an 'hasMany' relation between 'customers' and 'countries'. Limiting records for one customer to only two countries, and ordering them between 'primary' and 'alternate' is part of you business logic.

Related

MVC Database Model Dynamic Properties

He guys, so I need a little help with my database model for an mvc project I am working on.
Here is the situation:
I have a table called dbo.Clients that has the columns ClientName, PlanName, PlanPrice, PlanStartDate, PlanEndDate, and IsArchived.
For the fields ClientName, and IsArchived are only going to have one value in them that is subject to change. However, each client will have multiple PlanName, PlanPrice, PlanStartDate, and PlanEndDate values.
I have a ClientModel, ClientViewModel, ClientRepository, ClientService, and ClientController set up that successfully puts values into the database from the view.
The problem:
The way that I have done this is that I can only use one value for PlanName, PlanPrice, PlanStartDate, and PlanEndDate. For example lets say a client has bought Plan 1 and Plan 2 but I cannot store more than 1 plan.
What I want to do is make another table called Plans but I'm not quite sure how to use that in the MVC way to storing multiple values per client.
You need two tables. One will be a client master named something like Clients with the Columns Id, ClientName and IsArchived.
The other table will be something like ClientPlans with the columns ClientId, PlanName, PlanPrice, PlanStartDate, PlanEndDate
Ensure there's a Foreign Key relation between the Id in the Clients table and the ClientId in the ClientPlans table.
This can be refactored further to have a separate table for Plans (Id,PlanName, PlanPrice, PlanStartDate, PlanEndDate) and a transaction table called ClientPlans containing ClientId and PlanId with the appropriate relationships set.

In Rails, how do you swap a new object for an existing one?

I have the following nested model relationship:
Countries (id, name)
Provinces (id, country_id, name)
Cities (id, province_id, name)
I have validates_uniqueness_of constraint on the name fields for each model in the relationship and a unique index on the name columns in the database.
I want to swap a new object created with the same name as an existing record at some point before it's validated. In other words, if a user attempts to add a city, province, country combination that has already been added, I want to country model to return a reference to the corresponding existing model records instead of failing validation before save.
I'm having trouble using the model callbacks (after_initialize, before_validation, etc.) and I wasn't able to get Country.find_or_initialize_by_name to work with the nested models... any suggestions?
What you are trying to do sounds pretty hard and will probably require you to know a lot of the internal implementation details of ActiveRecord::Base.
Instead, could you do something like this?
#country = Country.find_or_initialize_by_name(params[:name])
...
#country.save
EDIT:
ActiveRecord has find_or_create_by_XXX and find_or_initialize_by_XXX functions built in, so there is no need to add a function to the model. For more info see the "Dynamic attribute-based finders" section of http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Rails ActiveRecord Question

Single Table Inheritance using ActiveRecord. Since we can use #test = Employee.all and find all the employees created. How does rails do this? Since we only use a User Table. How does it know about employees and retrieve only employees? Rails Magic? Explanation anyone? Thank you in advance.
Base Class : Person (inherits ActiveRecord)
Sub-Class: Employee, Supervisor, Manager (each inherit Person)
So my Person table needs to have a _type and _id field to make the table polymorphic.
My next question is how do I get Employee Associated to the Person table and when you save an employee, how do you get it to actually put in Employee in the person_type field?
To indicate to Ruby on Rails that the
users table needs to support Single
Table Inheritance you need to add a
column named ‘type’ to the users
table. Here is my users table
definition:
CREATE TABLE users ( id INT NOT
NULL AUTO_INCREMENT, user
VARCHAR(15) NOT NULL UNIQUE, pass
VARCHAR(40) NOT NULL, type
VARCHAR(20) NOT NULL, PRIMARY KEY (id) );
In the column named type you
should store the name of the class,
the class type, that should be used
for each user. To mark an certain user
as an admin set his type to
‘Administrator’. By setting a user’s
type to ‘Administrator’ you are giving
him full administrator privileges as
defined in your Administrator model
class.
http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/
Single table inheritance uses a type column on the table to indicate the type of the object. ActiveRecord knows that your Employee class is using single table inheritance (it has no matching table and the users/people table has a type column).
So when you ask for Employee.all it knows to looks for all entries in the users/people table where type == 'Employee'.
If you look at the logs the SQL will be displayed for these queries and you'll see the 'magic' happening.

Grails - Need to restrict fetched rows based on condition on join table

I have these two domains Car and Driver which have many-to-many relationship. This association is defined in table tblCarsDrivers which has, not surprisingly, primary keys of both the tables BUT additionally also has another boolean field deleted. Herein lies the problem. When I find/get query on domain Car, I am fetched all related drivers irrespective of their deleted status in tblCarsDrivers, which is expected.
I need to put a clause/constraint to
exclude the deleted associations from the
list of fetched records.
PS: I tried using an association domain CarDriver in joinTable name but that seems not to work. Apparently it expects only table names, not maps.
PPS: I know its unnatural to have any other fields besides the mapping keys in mapping table but this is how I got it and it cant be changed.
Car domain is defined as such -
class Car {
Integer id
String name
static hasMany = [drivers:Driver]
static mapping = {
table 'tblCars'
version false
drivers joinTable:[name: 'tblCarsDrivers',column:'driverid',key:'carid']
}
}
Thanks!
I know its unnatural to have any other
fields besides the mapping keys in
mapping table but this is how I got it
and it cant be changed.
This is not at all unusual. If you want to store properties about the relationship, this is the obvious solution. You should reinstate your association domain CarDriver which has a deleted property in addition to a relationship to Car and Driver, and you should then be able to write a query which excludes the deleted drivers.
A comprehensive example of how to define such a mapping is provided here.

What am I missing with my Entity Framework?

I have asp.net membership and I use the built in Create user method since it is convenient now after this depending on the user I want to add 2 more fields to the aspnet_UserTable.
In my aspnet_user Table I have like this
// All Standard Fields that come with this table
ClubID<nullable)
ClubName <nullable)
I have a table that relates this
Club Table
ClubID<PK>
ClubName
So this relationship forms that one club can have many users. But one user can only have 1 club.
So now I been trying to figure out how to add the ClubID to the aspnet Usertable since it does not show up in the Entity Framework Diagram since it does not show FK.
// Note in this case I am just using EF made to create but in reality I will use the Membership.Create.
aspnet_Users test = aspnet_Users.Createaspnet_Users(Guid.NewGuid(), Guid.NewGuid(), "myTest5", "mytest5", false, DateTime.Now);
test.Club = Club.CreateClub("One224", "Two224");
test.ClubName = "go";
MyEntities.AddToaspnet_Users(test);
MyrEntities.SaveChanges();
So what I have works but it just makes no sense and I hope there is a better way. Like I try to create the club and then stick it in the test.club.
This add's the ClubID primary key but does not add the clubName.
So then I have to add the club name separately. Like why? Is there not a better way?
I also prefer linq method syntax so if it is needed and you know this syntax can you please write it in that.
I would recommend a few things.
One: Strongly consider not adding columns to the aspnet_* tables. If you ever want to change your authentication method down the road you'll be stuck lugging those tables around with you even though you won't need them anymore. Also, there may be a new, better version of the membership provider one day that you won't be able to upgrade because you have customized the membership schema.
Two: Instead, why not create a new table called User (or something of your liking) that has your own primary key but links back to the ASP.NET Membership unique key (the guid).
Your table might look like
User
UserId (PK)
AuthenticationUserId (FK back to aspnet_User table)
ClubId (FK back to your club table)
Three: I don't understand why you've repeated ClubName both in your user table and in your Club table. You really only need to define the ClubName once, right? Keep your Club table how it is but remove the ClubName column from the user table.
Your code above for associating the club with the user is correct and works because that's how the Entity Framework works. You're associating entities with each other and are abstracted from some of the relational aspects of your data schema. It's a little strange to get used to it first but it does work.

Resources