Questions tagged [foreign-keys]
3341 questions
1
votes
1
answer
26
Views
Django foreign-key many to one relationship displaying on template
I'm trying to display job offers that are in relation ship with Company (Many To One) but I'm not able to do it. I've tried many loops but I'm not even getting queryset so I must doing it wrong but can't solve what I'm doing wrong.
My files
models.py
class Company(models.Model):
# field person with...
1
votes
1
answer
29
Views
How do I reference the “many” of “one-to-many” relationships in Django/Python?
I'm using Python 3.7 and Django. I have the below two models ...
class Article(models.Model):
title = models.TextField(default='', null=False)
class ArticleStat(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats')
elapsed_time_in_seconds = model...
1
votes
3
answer
92
Views
How to enforce by constraint that a referenced row also has a given type
I have multiple tables B,C,D ... referencing one another table A.
Let's just look at A and B:
CREATE TABLE A (
ID int PRIMARY KEY
, TYPE enum_type
);
CREATE TABLE B (
A_ID int REFERENCES A(ID)
);
Is it possible to check that A has always one specific TYPE when referenced by table B?
every row in A r...
1
votes
1
answer
41
Views
How to pass two different arguments in a single function in django?
Python newbie here, I am trying to create a web-app where shippers can post their truck-loads on sale and accept bids from transporters, and the transporters can post their bids on loads.
I have a list view function in my views.py, where a shipper can see all the bids posted by different suppliers,...
1
votes
2
answer
40
Views
Is it possible to insert row into the child table of FOREIGN KEY?
I have three tables in my database:
COMPANY(ID, NAME)
COUPON(ID, TITLE)
COMPANY_COUPON(COMPANY_ID, COUPON_ID)
Company can create coupons, so when it creates coupon, coupon's ID and ID of the company will be added into COMPANY_COUPON table. When company deletes coupon it also will be deleted fr...
1
votes
3
answer
50
Views
SQL selecting by many related foreign keys
In the beginning I'd like to mention, that I was trying to search for simillar problems but I didn't found the solution. I am doing my best to select disease from my database by typing in few id keys from sympthoms table. The relation between Disease and Sympthoms tables are many-to-many with connec...
0
votes
0
answer
4
Views
how to serialize entities that have a one to many relationship and a pagination in entity framework?
I have a two Model for two table having foreign key relationship. I have to get record from both table in single request.
The structure of model is as follows:-
EmployeeRecord.cs
public partial class EmployeeRecord
{
[System.Diagnostics.CodeAnalysis.SuppressMessage('Microsoft.Usage', 'CA2214:DoNotCa...
1
votes
0
answer
19
Views
flask mysqldb call a related table
Flask-mysqldb
Is there a way to call the related table without making a new query? if it's stored within the teacher object or something.
So I have the id under 'teacher' and they have a relation in MySQL.
{% for class1 in classes %}
{{class1.name}}
{{class1.code}}
{{class1.teacher}}
Outputs: 'Class...
1
votes
2
answer
47
Views
one to many And one to many relationship laravel
This is projects migrate
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('start_date');
$table->string('end_date');
$table->string('con');
$table->timestamps();
});
and this is timesheets migrate
Schema::create('timesheets', f...
1
votes
0
answer
296
Views
How to solve a sqlalchemy.exc.AmbiguousForeignKeysError in SQLalchemy?
I am learning SQLalchemy, so I decided to make a small database with a few tables in order to understand the way it works. In the docs and tutorials it all seems so clear, but when I start coding, I get long error messages, and right now I am stuck with this one.
I am trying to create 3 related tab...
1
votes
0
answer
59
Views
What is the best way to index several foreign keys?
Learning Oracle basics, I learned that foreign keys should be indexed, thanks to this question.
However if I have a table with several foreign keys, should I create 1 index for each foreign key or 1 index for the entire table ?
For example, I have the table A(a,b,c,d), b and c being foreign keys on...
1
votes
1
answer
15
Views
How to check which foreign key yelds the results
Let's suppose I have a database with 4 tables, for cataloguing books. For every book I want to store the title, one or more authors, and one or more translators.
The structure is as follows:
CREATE TABLE `book` (
`book_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`title` TEXT
);
CREATE T...
1
votes
1
answer
78
Views
Doctrine : UniqueEntity on foreign property?
Is it possible to use a UniqueEntity annotation on a foreign object property ?
For example I have two class :
class A {
private $id;
private $num;
/**
* @ORM\ManyToOne(targetEntity='B' ....)
*/
private $b;
...
}
class B {
private $id;
private $sku;
...
}
I need to prevent users entering a A.num alre...
1
votes
0
answer
85
Views
Entity Framework cannot add foreign key on inherited columns
I am using EF 6.2.
I have an abstract base class, let's call it Person, which some classes inherit from, let's say Student and Teacher. Each person can have two addresses. This gives something like that:
public abstract class Person
{
...
public int LocationAddressId { get; set; }
public Address Loc...
1
votes
1
answer
21
Views
Assign primary key in one DB as foreign key in other DB
A Primary Key column in table A in database One...I want assign it as foreign key in table B in database Two...
both DB in same server, I'm using HSQLDB server 2.4 :
A- what would be the query?
B- I saw this way and I read it's not good practice,
Can we use join for two different database tables?
tw...
1
votes
2
answer
693
Views
Laravel Foreign key Referencing table in External database?
I'm new to Laravel and databases in general. I'm writing a web application for student evaluations. I have an existing MySQL database that contains everything I need already; however, I am using Laravel's auth user table and trying to add a foreign key that references a Teacher table in the MySQL da...
1
votes
1
answer
21
Views
sql integrity constraint parent key not found
I am trying to do something so simple creating and insert 4 tables with their data. I have spent hours on the web researching integrity constraints and tried several IDE's in case there's a bug but nothing seems to work. Code is shows below (excuted in order).
I can insert the data for the first two...
1
votes
1
answer
40
Views
How to create a hasOne association that joins on multiple foreign keys via an OR condition?
I'm trying to join a table (Connections) twice from another table (Ports).
The conditions are:
One port can have one or no connection
One connection has one from-port and one to-port
The structure is:
Table Ports:
id
number
Table Connections:
id
port_from_id
port_to_id
name
So now I want to join fro...
1
votes
0
answer
48
Views
JPA @JoinTable do not create foreign keys in phpmyadmin
I am new to Hibernate and JPA.
I would like to create a @ManyToMany relationship between the Movie
and Actor class.
In the hibernate.cfg.xml file, I have set the following configuration:
update
Here a code snapshot from the Movie and Actor entities.
@Entity
public class Movie {
@Id
@GeneratedValue(...
1
votes
0
answer
54
Views
Entity Framework 6 (code-first) - composite foreign key
I'm working with Entity Framework (code-first) for the first time and I can't figure out how to accomplish a specific foreign key.
My code looks something like this:
public class Customer
{
[Key]
[Index('IX_Customer_Entity', IsUnique = true, Order = 1)]
public int CustomerID { get; set; }
[Index('IX...
1
votes
0
answer
100
Views
SQL Server 2017 Foreign Key Relationship Window - Does it have typo?
I noticed Foreign Key Relationship window in SQL Server 2017 there is a collapsible part called INSERT And UPDATE Specification and when you open this part there are two items under it which are:Delete Rule and Update Rule.
Delete Rule and Update Rule makes sense. But I think the INSERT And UPDATE S...
1
votes
1
answer
221
Views
Symfony - SQLSTATE-23000 : Integrity constraint violation: 1022 Can't write duplicate key
I would like to use relations in my Doctrine Product, ProductType and Manufacturer entities, but when i do php bin/console doctrine:migrations:migrate I get this error :
-> ALTER TABLE product ADD CONSTRAINT FK_D34A04ADA23B42D FOREIGN KEY (manufacturer_id) REFERENCES manufacturer (id)
Migration 2018...
1
votes
0
answer
40
Views
Write a MySQL join query for retrieve project information
I need to write a MySQL join query for retrieve project information as this image below.
project manager able to get list of each developer's workingHours, Overtime, Descriptions, Contributions for specific project his assigned. This is my database table structure.
Can anyone tell me how to to thi...
1
votes
1
answer
58
Views
Django M2M relationships: Use just one intermediary table or one per entity pair?
When creating many to many relationships we use an intermediary table. Lets say I use the following entities video, category, tag, and VideoCategory, VideoTag to create the relations.
I'm assuming that many tags/categories can have many videos and vice-versa.
And I do it with through keyword 'cause...
1
votes
1
answer
476
Views
How to use where clause in eloquent relationships in laravel
I'm trying to access company variable in laravel eloquent relationship but i'm getting error undefined variable.
Controller
$assignedCases = AddressCaseAssign::with(['addresses' => function ($query) {
$query->where('company_id', '=',$request->company);
}])->where('user_id',$request->executive)
->get...
1
votes
0
answer
60
Views
Realm optional way for foreign key
I am new to Realm. Actually, Realm doesn't provide us functionality for Foreign key and I want to use the functionality of Foreign key.
So Here is my model :
public class CategoryInfo extends RealmObject {
@SerializedName('name')
String name;
@SerializedName('id')
int id;
@SerializedName('sub_catego...
1
votes
0
answer
34
Views
How to show link to all objects with same foreign key from Django Admin change page
I am trying to link directly from the change page of a Company Year in Django Admin to the other changepages of Company Year that have the same Company as a foreign key.
Currently I have a link from the change page to the company page, and there I have links to all Company Years related to this comp...
1
votes
1
answer
36
Views
EntityFramework - Composite keys and foreign key
Im working on a project and I'm using Entity Framework with the code first approach. My first model, Player, has two string for its ids (I didnt choose that and I know its a bad approach) :
public class Player()
{
[Key, Column(Order=0)]
public string Name { get; set;}
[Key, Column(Order=1)]
public s...
1
votes
1
answer
328
Views
EF Core one-to-many without Foreign Key (FK)
Are there ways to make one-to-many (abstract) relation without using SQL foreign keys?
I know it could be made by joining 2 non-related tables. But is it possible to use EF Core default navigation tools?
1
votes
0
answer
30
Views
PHP/mySQL - Linking answer posts to questions
This should be easy for me to do, in fact I've managed to do it successfully before (Thanks to some helpful people around here.)
In my video-hosting website, videos are posted directly in response to a request for help in hobby-making. To be exact, you read a request on the site and on that same pag...
1
votes
0
answer
59
Views
how to create a model object that can handle a single foreign key for people and companies
I am creating an investor object. Investors can be people or companies.
How can I create a model object that could represent either of these types in django?
Here are a few ways I was thinking:
1. Having two non required foreign keys:
class Investor(models.Model):
company = models.ForeignKey('comp...
1
votes
1
answer
244
Views
Android room foreign key constraint failed 787. Folder system
How can I realize folder system for db in Room? I want create folders and store in this some data. Nested folders is not necessary.
Before I use table with data (webSites) and folders table, then I create 3rd table WebSitesWithFolders, where I storing webSites_id and folders_id. But when I update or...
1
votes
1
answer
322
Views
Django: “Cannot add foreign key constraint” when creating test tables before running unit tests
I am trying to run unit tests that I've written for my Django project, but testing fails at the database creation stage. I have a single database 'test', one of which as a foreign key relationship with another. I run the following:
python3 manage.py test --settings myapp.settings_test
And see the fo...
1
votes
0
answer
212
Views
Spring boot and hibernate web app - Cannot add foreign key constraint error
I am using spring boot and hibernate for a simple web app. When I am trying to run it I get this error 3 times.
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTarg...
1
votes
1
answer
50
Views
Using CONSTRAINT alogn with FOREIGN KEY
I'm trying to understand the difference between creating a FOREIGN KEY this way:
CREATE TABLE child(
id_child INT NOT NULL,
id_parent INT
FOREIGN KEY(id_parent) REFERENCES parent(id_parent));
rather than this one:
CREATE TABLE child(
id_child INT NOT NULL,
id_parent INT
CONSTRAINT FK_id_pare...
1
votes
0
answer
53
Views
Can I dynamically assign the Class of a Laravel Eloquent relationship?
This question comes forth from How can I transform / cast a PHP parent object to a child object?
Currently I have this code:
class Page extends Model {
// relation 1, 2, 3 that are always present
}
class ArticlePage extends Page {
// relation 4 and 5, that are only present on an ArticlePage
}
class...
1
votes
1
answer
871
Views
How does primary key and foreign key constraints works in hive?
Primary key and foreign key constraints feature are available from Hive 2.1 version. How this constraint relation works in the hive, is it similar as in the normal database. Hive works on 'Schema on reading', So How these constraints effects while loading or deleting the data?
1
votes
0
answer
17
Views
One to Many and One to One on same entities
Business Case
We have a shirt that can be ordered in several different colors: Yello; White; Orange; Blue; Green; Red;
However, only one color can be selected as the default for a shirt.
Implementation
Here is what I have so far:
public class Shirt
{
public int Id { get; set; }
public string Sku { g...
1
votes
0
answer
164
Views
I can't save to SQLAlchemy when the foreignkey is included
I can create my tables with SQL Alchemy. Here is my full code:
from sqlalchemy import create_engine, Column, Integer, ForeignKey,
String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'perso...
1
votes
1
answer
249
Views
How to insert foreign key in jsp
I am developing an online event management web app for my college project. When a event organizer registers in app their values are stored in MySQL database with o_id as primary key which is auto incremented. But my problem is when the organizer logs in and want to advertise their event he has to fi...