Navigation Property Mapping on two different fields - entity-framework

I have a squirrely situation, where in some relationships a tables ID field is used as the key reference. But in other, older implementations, the Name field was used as the relationship mapping.
FileType:
ID | Name |....
FileTypeDetails:
ID | FileTypeId | ....
PostingGroupDetails :
FileType | ....
PostingGroupDetails.FileType has a map to FileType.Name. FileTypeDetails.FileTypeId maps to FileType.ID.
I am using the Fluent API structure to do the mappings manually but am running into a wall with this relationship mapping.
I though that doing a multi-key mapping might work but am unsure. Still in the design stage, and about to implement the interface side of the project.
Any ideas on how i make the mapping available to both, until we can consolidate the relationship mapping to one or the other?
EF Implementation:
FileType
I know FileType is currently Optional, but its only a direct correlation to the Table design. I am flagging it for schema updating, currently in practice it is a required field in order for the entry to be submitted.
ToTable( "FileType" , "Int" );
HasKey( ftd => ftd.ID );
Property( ftd => ftd.ID ).HasColumnName( "ID" )
.HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
Property( ftd => ftd.Name).HasColumnName( "Name" )
.IsOptional();
//Navigation Properties
HasMany( ftd => ftd.FileNames )
.WithRequired( fn => fn.FileType );
HasMany( ftd => ftd.PostingGroupDetails )
.WithRequired( pgd => pgd.FileTypeDetails );
FileNames
FileNames.FileTypeID relates to FileType.ID
ToTable( "FileNames" , "Int" );
HasKey( fn => fn.ID );
Property( fn => fn.ID ).HasColumnName( "ID" )
.HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
Property( fn => fn.FileTypeID ).HasColumnName( "FileTypeID" )
.IsRequired();
//Navigation Properties
HasRequired( fn => fn.FileType )
.WithMany( ftd => ftd.FileNames )
.HasForeignKey( fn => fn.FileTypeID );
PostingGroupDetails
PostingGroupDetails.FileType relates to FileType.Name
ToTable( "PostingGroupDetails " , "Int" );
HasKey( pgd => pgd.ID );
Property( pgd => pgd.ID ).HasColumnName( "ID" )
.HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );
//Required Properties
Property( pgd => pgd.FileType ).HasColumnName( "FileType" )
.IsRequired();
//Navigation Properties
HasRequired( pgd => pgd.FileTypeDetails )
.WithMany( ftd => ftd.PostingGroupDetails );
Any ideas would be greatly appreciated. Refactoring the Database structure is not an option right now, but it is on the plate to be done.

Entity Framework allows for differences between the database model and the class model (or conceptual model). You can define primary keys in the conceptual model that don't exist, or aren't even constrained as unique, in the data model.
So you can (and have to) choose which fields you want to mark as PK in the conceptual model. You can only define associations to PKs that are defined in the conceptual model and there can only be one PK per entity. So for FileType you must either take ID or Name and then you can define an association with FileTypeDetails or PostingGroupDetails. For the other associations you know exist you'll have to write join queries. As in
from x in X
join y from Y on x.Name equals y.Name
select ...

Related

How to setup these relations correct in Backpack for Laravel

I have a Problem with relations in Laravel / with Backpack for Laravel.
This program is for creating menues for my dad´s restaurant.
I have these tables:
- dishes (Table with the Names of the Dishes)
-- id (auto inc)
-- menuname (Name of the Dish)
- weeklymenues
-- id (auto inc)
-- start_date (Monday of the selected week)
-- end_date (Friday of the selected week)
-- menu_monday (There should be the id of the dish)
-- menu_tuesday (...)
-- menu_wednesday (...)
.....
How can i do that correctly?
In the CRUD Controller i am setting the Field:
$this->crud->addField([
'label' => "Monday",
'type' => 'select2',
'name' => 'menu_mondy', // the db column for the foreign key
'entity' => 'menu', // the method that defines the relationship in your Model
'attribute' => 'menuname', // foreign key attribute that is shown to user
'model' => "App\Models\Menu" // foreign key model
]);
And in the menues model i have set this relation:
public function menu() {
return $this->belongsTo('\App\Models\Menu');
}
Everytime I want to save the CRUD, the program wants to save something in the dishes table:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dish_id' in 'field list' (SQL: update `weeklymenues` set `dish_id` = 1, `weeklymenues`.`updated_at` = 2019-06-25 14:13:14 where `id` = 15)
What am I doing wrong? How can I set the relations correct?
Thanks in advance!!
Are "dishes" (from the table definition) and "Menu" (from the code) actually the same thing?
In your field definition, you set the model to be the "menu" class, shouldn't it be the "dishes" class?
I would have used the relationship type
CRUD::addField([
'label' => 'Monday',
'type' => 'relationship',
'name' => 'menu', // the method that defines the relationship in your Model
'attribute' => 'menuname', // foreign key attribute that is shown to user
'model' => \App\Models\dishes::class, // foreign key model
'placeholder' => 'Select a dish for Monday'
]);
---
-c:\xampp\htdocs\bpwebsite\app\Models\weeklymenues.php
---
protected $fillable = ['start_date', 'end_date', 'menu_monday']
---

How can I expose many-to-many tag-style relationship in a Catalyst app?

I'm building a database application in Catalyst, using jqGrid to do the messy work of handling the display of data. I've got almost everything working, except for being able to filter search results by "tags". I have three tables, with relationships like this:
package MyApp::Schema::Result::Project;
...
__PACKAGE__->has_many(
"job_flags",
"MyApp::Schema::Result::ProjectFlag",
{ "foreign.project_id" => "self.id" },
{ cascade_copy => 0, cascade_delete => 0 },
);
...
__PACKAGE__->many_to_many(flags => 'project_flags', 'flag');
1;
and
package MyApp::Schema::Result::Flag;
...
__PACKAGE__->has_many(
"project_flags",
"MyApp::Schema::Result::ProjectFlag",
{ "foreign.flag_id" => "self.id" },
{ cascade_copy => 0, cascade_delete => 0 },
);
...
__PACKAGE__->many_to_many(projects => 'project_flags', 'project');
1;
and finally, the join table
package MyApp::Schema::Result::ProjectFlag;
...
__PACKAGE__->belongs_to(
"flag",
"MyApp::Schema::Result::Flag",
{ id => "flag_id" },
{ is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);
...
__PACKAGE__->belongs_to(
"project",
"MyApp::Schema::Result::Project",
{ id => "project_id" },
{ is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);
...
1;
In my controller that provides the JSON data to jqGrid, I use Catalyst::TraitFor::Controller::jQuery::jqGrid::Search to translate the request parameters generated by jqGrid into DBIx::Class-style queries:
my $search_filter = $self->jqGrid_search($c->req->params);
my $project_rs = $c->model('DB::Project')->search(
$search_filter, {
join => 'project_flags',
group_by => 'id',
},
);
which is then passed on to the jqGrid page generator:
$project_rs = $self->jqgrid_page($c, $project_rs);
and then I iterate over the result set and build my jqGrid columns.
On the HTML side, I am able to build a JSON string like
{"groupOp":"AND","rules":[{"field":"project_flags.flag_id","op":"eq","data":"2"}]}
and, in this case, show Projects having a row in project_flags with flag id of 2.
I absolutely know I'm not doing this correctly! All of the documentation I can find on Catalyst and DBIx::Class demonstrates similar ideas, but I just can't understand how to apply them to this situation (not that I haven't tried).
How would I go about building "has_flag($flag_id)"-type accessors, and then be able to use them from within jqGrid's API? Where in my Catalyst app would this belong?
One of the ways I'd like to filter is by the lack of a particular flag also.
I've got to be honest with you, I'm not entirely sure I understand your question. It seems to be what you're asking has more to do with DBIx::Class than Catalyst--the latter I know very little about, the former I am learning more about every day. With that in mind, here's my best attempt at answering your question. I am using Mojolicious as the MVC, since that's what I know best.
First, I start by creating a many-to-many database:
CREATE TABLE project(
id INTEGER PRIMARY KEY,
name text
);
CREATE TABLE flag(
id INTEGER PRIMARY KEY,
name text
);
CREATE TABLE project_flag(
project_id integer not null,
flag_id integer not null,
FOREIGN KEY(project_id) REFERENCES project(id),
FOREIGN KEY(flag_id) REFERENCES flag(id)
);
INSERT INTO project (id,name) VALUES (1,'project1');
INSERT INTO project (id,name) VALUES (2,'project2');
INSERT INTO project (id,name) VALUES (3,'project3');
INSERT INTO flag (id,name) VALUES (1,'flag1');
INSERT INTO flag (id,name) VALUES (2,'flag2');
INSERT INTO flag (id,name) VALUES (3,'flag3');
INSERT INTO flag (id,name) VALUES (4,'flag4');
INSERT INTO project_flag (project_id,flag_id) VALUES (1,1);
INSERT INTO project_flag (project_id,flag_id) VALUES (1,2);
INSERT INTO project_flag (project_id,flag_id) VALUES (1,3);
INSERT INTO project_flag (project_id,flag_id) VALUES (1,4);
INSERT INTO project_flag (project_id,flag_id) VALUES (2,1);
INSERT INTO project_flag (project_id,flag_id) VALUES (2,4);
And here is my Perl (Mojolicious) code:
#!/usr/bin/env perl
use Mojolicious::Lite;
use Schema;
helper db => sub {
return Schema->connect('dbi:SQLite:test.db');
};
get '/' => sub {
my $self = shift;
my $rs = $self->db->resultset('Project')->search(
{ 'me.name' => 'project3' },
{
join => { 'project_flags' => 'flag' },
select => ['me.name', 'flag.name'],
as => ['project', 'flag']
}
);
$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
$self->render( json => [ $rs->all ] );
};
app->start;
And here's the JSON output (pretty print) from project1 (has flags related to it):
[
{
"project":"project1",
"flag":"flag1"
},
{
"flag":"flag2",
"project":"project1"
},
{
"project":"project1",
"flag":"flag3"
},
{
"flag":"flag4",
"project":"project1"
}
]
And here is JSON for project3, with no relationship to any flags:
[
{
"project":"project3",
"flag":null
}
]
I put the files on Github, so you can check them out if you'd like.
In your given situation, say they've typed the word 'c++' into the filter, and you want to return everything that has been tagged 'c++', then:
my $rs = $self->db->resultset('Tag')->search(
{ 'me.name' => 'c++' },
{
join => { 'project_flags' => 'project' },
select => ['me.name', 'project.name'],
as => ['tag', 'project']
}
);
$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
$self->render( json => [ $rs->all ] );
If you wanted to return all columns, use prefetch rather than join. Also, if you'd like to support the Autosearch functionality, change search to search_like, like so:
my $rs = $self->db->resultset('Tag')->search_like(
{ 'me.name' => $search_filter.'%' },
I hope that if I did not answer your question what I have given is at least a push in the right direction.

FuelPHP ORM Primary Key on model cannot be changed

I've been banging my head with this ORM error:
Fuel\Core\FuelException [ Error ]: Primary key on model Model_CustomValue cannot be changed.
Here are relevant info from my models I'm having issues with:
<?php
use Orm\Model;
class Model_Purchase extends Model
{
protected static $_has_many = array(
'customvalues' => array(
'model_to' => 'Model_CustomValue',
'key_to' => 'purchase_id',
'cascade_delete' => true,
)
);
protected static $_properties = array(
'id',
'customer_id',
'payment_id',
'audit_id',
'created_at',
'updated_at',
);
<?php
use Orm\Model;
class Model_CustomValue extends Model
{
protected static $_table_name = 'customvalues';
protected static $_primary_key = array('purchase_id', 'customfield_id');
protected static $_belongs_to = array(
'purchase' => array(
'key_from' => 'purchase_id',
'model_to' => 'Model_Purchase',
'key_to' => 'id',
),
);
When trying to save the Model_Purchase with an array of Model_CustomValue objects as a property named 'customvalues' on the $purchase object, I get the "Primary key on model Model_CustomValue cannot be changed."
I've tried swapping the key_from/to in the "belongs_to" on the Model_CustomValue, but to no avail.
I'm using Fuel 1.6 (hash: 6e6d764)
Please let me know if more information would be helpful, and I'll provide.
From the FuelPHP forum thread, Harro answered:
You can not have a column which is at the same time FK and PK. Which
you have on your Model_CustomValue.
The reason for that is that when you disconnect a relation, the FK
will be set to NULL, which should not happen with a PK.
I then clarified, for those of us who may need specific examples from the original example, I confirmed the following:
So just re-stating why that's not allowed:
Model_CustomValue uses the "purchase_id" as part of its PK as well as the FK to Model_Purchase. And if the two Models were to be unlinked, that would lead to a null portion of the PK for Model_CustomValue -- which obviously isn't allowed.

CakePHP 2.2 with PostgreSQL Failed new row insert - Database Error: Undefined table: 7 ERROR: relation "table_id_seq" does not exist

My problem is as follows.
After deleting multiple rows from table, inserting new record into same table results in error.
Database Error
Error: SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "order_details_id_seq" does not exist
Table
CREATE TABLE schema.order_details (
id serial NOT NULL,
order_id integer NOT NULL,
field_1 integer,
field_2 real,
field_3 character varying(15),
CONSTRAINT order_details_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
Insert is
INSERT INTO "schema"."order_details" ("order_id", "field_1", "field_2", "field_3")
VALUES (37, 1, 2, 'value');
Sequence "schema"."order_details_id_seq" in used schema exists.
CREATE SEQUENCE schema.order_details_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 37
CACHE 1;
Models.
// Model
class Order extends AppModel {
public $useDbConfig = 'other_data';
public $hasMany = array(
'OrderDetail' => array(
'className' => 'OrderDetail',
'foreignKey' => 'order_id',
'dependent' => true,
'order' => array(
'OrderDetail.order_id',
'OrderDetail.field_1'
))
);
class OrderDetail extends AppModel {
public $useDbConfig = 'other_data';
public $belongsTo = array(
'Order' => array(
'className' => 'Order',
'foreignKey' => 'order_id',
'dependent' => true
),
// model Order save code on recreation of order
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $this->id));
At this point tried to insert $this->OrderDetail->query('VACUUM FULL ANALYZE order_details'); with no effect
foreach ($details as $d) {
$this->OrderDetail->create();
$this->OrderDetail->save($d /*array(
'order_id' => $this->id,
'field_1' => 1,
'field_2' => 2,
'field_3' => 'value'
)*/);
}
I get error on first foreach loop.
Weirdest thing is that problem appears and disappears after some time randomly.
Any suggestions on what it could be and how to get rid of it?
Currently solved problem using code.
$this->Order->id = $id;
$this->Order->delete();
It fires 2 queries for each row (100 extra in my case!) of delete statements instead of two in case of
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $id));
So for this time it has space for improvement.
EDIT: Currently code works as it should with tweaked DboSource.
It seems that cake was looking in public schema for sequence where it is not located.
Fixed it by tweaking to include schema name in last insert getter inf file Model/Datasource/DboSource.php create method with this diff
## -1006,7 +1006,7 ##
if ($this->execute($this->renderStatement('create', $query))) {
if (empty($id)) {
- $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
+ $id = $this->lastInsertId($this->fullTableName($model, false, true), $model->primaryKey);
}
$model->setInsertID($id);
$model->id = $id;
I know that modifying core is not the way to go, but as long as it is working it is fine with me.
This happened to me because I modified the name of the table, but PostgreSQL did not change the name of the sequences. Knowing this, I changed the name of the sequences that affected this table and it was resolved.
To prevent this error, use this convention to name your sequence when using cakephp: table_name_id_seq. For example:
table name: user
sequence name should be: user_id_seq
If you alredy have sequences, you can rename it in posgres like this
alter sequence user_seq rename to user_id_seq
I'm not a fun of this way to name sequence but it prenvent this kind of errors in my case

Yii fail to retrieve max column value

I have two models, one is Auction, the other is Bid.
An Auction has many Bids. they are associated by foreign key auction_id in Bid
Now, I want to find the max value of the Bid's price for each Auction.
$dataProvider = new CActiveDataProvider('Auction', array('criteria' => array(
'with' => array(
'bids' => array(
'alias'=>'b',
'group' => 'auction_id',
'select' => 'max(b.price) as maxprice'
)
)
)
)
);
And I have defined a maxprice property in Auction's model class.
However, if I try to retrieve the maxprice property, it returns NULL.
To be more specific, I render the $dataprovider to a view page, it fails to get the maxprice property.
PS:
I executed the query in mysql, the query result turns out to be correct.
So, there must be something wrong with the Yii code
SQL code:
SELECT `t`.`id` , max(b.price) as maxprice
FROM `auction` `t`
LEFT OUTER JOIN `bid` `b` ON (`b`.`auction_id`=`t`.`id`) GROUP BY auction_id
Put the value you want before the relation, like so:
$dataProvider = new CActiveDataProvider('Auction', array('criteria' => array(
'select' => 't.*, max(b.price) as maxprice',
'with' => array(
'bids' => array(
'alias'=>'b',
'group' => 'auction_id',
'together'=>true,
)
You can replace the "t.*" with specific field names if you like.
OR you can simply use the select, join and group attributes on your Auction model and skip the relation altogether.