what is local key in laravel eloquent - sql

http://laravel.com/docs/4.2/eloquent#relationships
what does local key mean in this thing? does it mean primary key of the table? or what? for example in this code
return $this->hasOne('Phone', 'foreign_key');
return $this->hasOne('Phone', 'foreign_key', 'local_key');

local_key is the primary key of your table. You only need to specify it if your primary key is not called id AND you do not have the $primaryKey property set in your model.

I believe everything is written in the doc:
ake note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association:
Which basically means that 'local_key' is the name of the table column in your db which is responsible to match the related entity (phone) with your current entity (user).
If you have a look at the db, I'm sure you'll find a table user with a phone_id column, try to change it to something else (like "phone" only) and your eloquent request will crash. Then change your call to return $this->hasOne('Phone', 'user_id', 'phone'); and this might work again.

Related

Domain Driven Design Auto Incremented Entity Key

Just starting with Domain Driven Design and I've learned that you should keep your model in a valid state and when creating a new instance of a class it's recomended to put all required attributes as constructor parameters.
But, when working with auto incremented keys I just have this new ID when I call an Add method from my persistent layer. If I instanciate my objects without a key, I think they will be in a invalid state because they need some sort of unique identifier.
How should I implement my architecture in order to have my IDs before creating a new instance of my entity ?
Generated Random IDs
The pragmatic approach here is to use random IDs and generate them before instantiating an entity, e.g. in a factory. GUIDs are a common choice.
And before you ask: No, you won't run out of GUIDs :-)
Sequential IDs with ID reservation
If you must use a sequential ID for some reason, then you still have options:
Query a sequence on the DB to get the next ID. This depends on your DB product, Oracle for example has them).
Create a table with an auto-increment key that you use only as key reservation table. To get an ID, insert a row into that table - the generated key is now reserved for you, so you can use it as ID for the entity.
Note that both approaches for sequential IDs require a DB round-trip before you even start creating the entity. This is why the random IDs are usually simpler. So if you can, use random IDs.
DB-generated IDs
Another possibility is to just live with the fact that you don't have the ID at creation time, but only when the insert operation on the DB succeeds. In my experience, this makes entity creation awkward to use, so I avoid it. But for very simple cases, it may be a valid approach.
IN adition to theDmi's comments
1) You can in your factory method make sure your entity gets stored to the database. This might or might not be applicable to your domain but if you are sure that entity is going to be saved that might be a valid approach
2) You can separate the ID from the primary key from the database. I've worked with a case there something was only an order if the customer payed and at that point it would be identified by it's invoice id (a sequentual ID). that doesn't mean in the database i would need an column ID which was also the primary key of the object. You could have a primary key in the database (random guid) and till have an ID (int?) to be sequentual and null if it hasn't be filled yet.

Entity Framework code-first: querying a view with no primary key

Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify.
But for views not having primary key is it still possible to query.
I try to find but always Entity Framework gives error saying:
Error: : EntityType 'ViewWeight' has no key defined. Define the key for this EntityType.
I understand key is important for tables, but for views just to read is there any hack or way to read the values without modifying the view itself.
It's not possible in Entity Framework to have Entities without primary key.
Try to get a possible unique key from the views, combining columns, ... to create a unique primary key.
If is not possible there is a workaround, if is only a queryable view, with out need to do other operations with retrieved values such delete or update. Modify the view to add NEWID() , it will generate a unique GUID ID for each row, use this new column as primary key for your entity.
CREATE VIEW FooView AS
SELECT SELECT NEWID() AS ID,
COLUMN_A,
COLUMN_B
.....
The problem is if you repeat the same query every time you will get different ID for the same row.
Updated
If you can't not modify the view you can use Entity with a raw Sql, create the raw sql as
List<MyView> myViewItems = context.MyView.SqlQuery("SELECT NEWID() AS ID, MyView.* FROM MyView").ToList();
In your models add
public Guid ID { get; set; }
And configure the new property as the primary key.
But be careful, because there is not compilation check with this kind of code.
I create the view which includes a primary key. Ensure that all fields in the view are of a specific data type:
Number(9) rather than Number, use CAST to get the type you want
Then add a disabled primary key constraint. It won't do anything except be recognized by entity framework as a key
alter view emp_view add constraint vemp_pk primary key (empno) disable

CakePHP Database Naming Convention

I had Read the CAKEPHP Convention.
So I changed from the wrong convention to the right.
However I still unsure If I name my ID correctly because now my model still need to use "$primaryKey" to override for the Delete Method.
Model: EventDate
Controller: EventDatesController
Database Table: event_dates
event_dates ID : event_date_id
Secondly, After I change the table col_id name , my Edit Method Query the Where clause for the primary key still remain old primary key name. Try to delete cache but still can't work.
SQL Query: SELECT `EventDate`.`event_date_id`, `EventDate`.`event_date`, `EventDate`.`Created`, `EventDate`.`modified` FROM `fyp_seatmanagment`.`event_dates` AS `EventDate` WHERE `EventDate`.`eventdate_id` = '65' LIMIT 1
As far as I know the naming convention for the primary key is just id. So your event_dates ID shout just be id instead of event_date_id.
To your second part:
You named your ID event_date_id but looking for eventdate_id in your where-clause. So you forgot a _ there. If you change your primary key to id(see above) then don't to forget to fix your statement.
Cake's naming conventions use id for primary keys. For foreign keys use _id prefixed with the singular snake cased related table name.
So for your EventDate model your primary key needs to be id.
As an example of a foreign key, if EventData belonged to an Event model then the foreign key would be event_id.
In your example you've confused primary and foreign keys which will cause you all sorts of headaches even if you try overriding the defaults.
You can read up more on Cake's naming conventions in the docs.

Create a new record with an assigned PK - Castle ActiveRecord

I have a table with a GUID primary key. In ActiveRecord it is setup with a PrimaryKeyType.GuidComb. Is it possible to create this record with a manually assigned PK? If I set the primary key in the record and run Create() a new ID is assigned. If I run Save() I get an error (as one would expect).
The why:
This table is in two databases. Records need to be copied between these two databases on occasion. I would like to retain the ID as the record moves across the DBs.
No. A primary key is either generated (e.g. GuidComb) or manually assigned, it can't be both. You could create two classes that inherited from a base class defining all properties except the primary key, then each of these two classes would define their primary key as assigned or generated. But I'd recommend using SQL here, as a single INSERT INTO ... SELECT will be more efficient than using NHibernate/ActiveRecord.
I ended up setting the PrimaryKeyType to Assigned. Then I handled it with an overrided Create function:
public override void Create() {
if (ID == default(Guid)) ID = GUIDGenerator.Generate();
base.Create();
}
It would have been better to put this in OnSave, but the primary key cannot be modified in the interceptor. This works for my application, however this code will only be called if the object is explicitly created. It will not work if the object is created by cascade.

Fluent-NHibernate table mapping with no primary key

I am trying to create a mapping to a database table that has no primary keys/references.
public class TestMap : ClassMap<<Test>Test> {
public TestMap() {
WithTable("TestTable");
Map(x => x.TestColumn);
}
}
This fails and expects id or composite-id. Is this possible in fluent nhibernate?
In Oracle at least, I have used "ROWID" for this. For mssql you might use the "ROW_NUMBER()" builtin function for readonly access to the table, but I haven't tried that...
No. You'll have to add a surrogate primary key, such as an identity column in SQL Server, to map this table. As far as I know, this isn't supported by NHibernate itself.
Why don't you have a primary key on this table?
This functionality isn't supported by nhibernate as far as I know. As a general rule of thumb, however, you should really always have some kind of ID and if you find yourself in a situation where you think you don't need one you should assess your data model. An ID, whether it be a table-specific primary key, or a surrogate key from another table, should exist. This not only ensures that nhibernate can process the table, but helps performance via indexing.
Before you start assuming nhibernate isn't going to fulfill your needs, consider why you don't have a key on the table and what kind of sense it makes not to have one.
If we can bring a column from table having no primary key/identity coulmn, then we can use fluent as below:
Id(x => x.TempID).Column("TempID");
If the table contains data that belongs to another entity, you could map it as a collection of components. Components are not identified by themselves, but they belong to another entity, which is identified.
You can map an entity to a table without keys defined in the database. I do so in legacy SQL Server databases. However, the table must have a candidate key (some set of columns that actually stores a unique combination of values). The concept of entity involves the notion of some kind of identity.
Instead of this, what you're trying in your code is to map an entity without identity, wich isn't possible.