I am trying to create a foreign key constraint between my two tables on Laravel 4, User and GP. A user can be associated with many GPs. The foreign key is 'Practice_ID' in the users table, which associates with the ID in the GP table.
public function up()
{
// Creates GP table
Schema::create('gp', function($ta)
{
$ta->bigIncrements('id');
$ta->string('address_1');
$ta->string('address_2');
$ta->string('address_3');
$ta->string('post_code');
$ta->timestamps();
});
// Creates the users table
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->string('confirmation_code');
$table->boolean('confirmed')->default(false);
$table->bigInteger('practice_id');
$table->foreign('practice_id')->references('id')->on('gp');
$table->timestamps();
});
// Creates password reminders table
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
The error I am getting is:
[Exception]
SQLSTATE[HY000]: General error: 1005 Can't create table
'doctor.#sql-3ac_a4' (errno: 150) (SQL: alter table users add
constraint users_practice_id_foreign foreign key (practice_id)
references gp (id)) (Bindings: array (
))
err 150 is most likely a data type mismatch.
delcare the foregin key as an unsigned int in the users table:
$table->integer('practice_id')->unsigned();
Also verify your db engine is INNODB that supports FK constraints
Related
I got lots of example to append/overwrite table in sql from AZ Databricks Notebook. But no single way to directly update, insert data using query or otherway.
ex. I want to update all row where (identity column)ID = 1143, so steps which I need to taken care are
val srMaster = "(SELECT ID, userid,statusid,bloburl,changedby FROM SRMaster WHERE ID = 1143) srMaster"
val srMasterTable = spark.read.jdbc(url=jdbcUrl, table=srMaster,
properties=connectionProperties)
srMasterTable.createOrReplaceTempView("srMasterTable")
val srMasterTableUpdated = spark.sql("SELECT userid,statusid,bloburl,140 AS changedby FROM srMasterTable")
import org.apache.spark.sql.SaveMode
srMasterTableUpdated.write.mode(SaveMode.Overwrite)
.jdbc(jdbcUrl, "[dbo].[SRMaster]", connectionProperties)
Is there any other sufficient way to achieve the same.
Note : Above code is also not working as SQLServerException: Could not drop object 'dbo.SRMaster' because it is referenced by a FOREIGN KEY constraint. , so it look like it drop table and recreate...not at all the solution.
You can use insert using a FROM statement.
Example: update values from another table in this table where a column matches.
INSERT INTO srMaster
FROM srMasterTable SELECT userid,statusid,bloburl,140 WHERE ID = 1143;
or
insert new values to rows where one of the existing column value matches
UPDATE srMaster SET userid = 1, statusid = 2, bloburl = 'https://url', changedby ='user' WHERE ID = '1143'
or just insert multiple values
INSERT INTO srMaster VALUES
(1, 10, 'https://url1','user1'),
(2, 11, 'https://url2','user2');
In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.
For a parent table, you can use the below query to get foreign key constraint names and the referencing table names:
SELECT name AS 'Foreign Key Constraint Name',
OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) AS 'Child Table'
FROM sys.foreign_keys
WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
OBJECT_NAME(referenced_object_id) = 'PARENT_TABLE'
Then you can alter the child table and drop the constraint by its name using the below statement:
ALTER TABLE dbo.childtable DROP CONSTRAINT FK_NAME;
I've created a MySQL Model with a few tables, some of them with fk's to another table. I usually export the SQL from MySQL Model to my database using the "Forward Engineer SQL CREATE Script" inside File -> Export -> Forward Engineer SQL CREATE Script. The problem here is that when I generate the creation script, all my fk's become unique. I didn't check UQ option in MySQL Model but it creates a script with unique fk's anyway, so, I need to change the SQL file generated and remove all the unwanted uniques. Anyone has a clue why this is happening?
Generated script:
CREATE TABLE IF NOT EXISTS `u514786799_detranleiloes`.`Lotes` (
`createdAt` DATE NOT NULL,
`updatedAt` DATE NOT NULL,
`id` INT UNIQUE NOT NULL AUTO_INCREMENT,
`LeiloesId` INT UNIQUE NOT NULL,
`conservado` TINYINT NULL,
`numero` INT NOT NULL,
`CRDsId` INT UNIQUE NULL,
PRIMARY KEY (`id`),
INDEX `fk_Lotes_Leiloes_idx` (`LeiloesId` ASC),
INDEX `fk_Lotes_CRDs1_idx` (`CRDsId` ASC),
CONSTRAINT `fk_Lotes_Leiloes`
FOREIGN KEY (`LeiloesId`)
REFERENCES `u514786799_detranleiloes`.`Leiloes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Lotes_CRDs1`
FOREIGN KEY (`CRDsId`)
REFERENCES `u514786799_detranleiloes`.`CRDs` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 1;
I am using the mobile application to query Dynamo DB tables. I have used the below query to fetch an item from the Dynamo DB Test table:
Test t = mapper.load(Test.class, DynamoDBHashKey, DynamoDBRangeKey);
My question is how to query an item from a Global Secondary Index? I have defined the annotations and parameters correctly in the Java class of the Test table.
Is there any other method to query Global Secondary Indexes and the Local Secondary Indexes.
The load api cannot be used to query GSI. The Query API can be used to query the GSI with key attributes.
Sample code:-
Map<String, AttributeValue> vals = new HashMap<>();
vals.put(":val1", new AttributeValue().withS("somevalue"));
DynamoDBQueryExpression<modelclass> queryExp = new DynamoDBQueryExpression<modelclass>()
.withKeyConditionExpression("category = :val1").withIndexName("indexname")
.withExpressionAttributeValues(vals);
dynamoDBMapper.query(modelclass.class, queryExp);
DynamodbQueryExpression class
I am using Django1.9 with Postgresql. This is my data model for the model "Feature" :
class Feature(models.Model):
image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,)
feature_value = HStoreField()
def save(self,*args,**kwargs):
if Feature.objects.filter(feature_value__has_keys=['size', 'quality' , 'format']):
super(Feature, self).save(*args, **kwargs)
else:
print("Incorrect key entered")
I am imposing a restriction on the feature_value such that only the keys that is allowed with Hstore are size , format and quality. I can do this while updating the database using Django-Admin. But I am not able to update the database directly using pgAdmin3 with the same restrictions i.e , I want to impose the same restrictions on the database level. How can I do that? Any suggestions?
You need to ALTER you Future table and add a constraint for feature_value field with such query:
ALTER TABLE your_feature_table
ADD CONSTRAINT restricted_keys
CHECK (
-- Check that 'feature_value' contains all specified keys
feature_value::hstore ?& ARRAY['size', 'format', 'quality']
AND
-- and that number of keys is three
array_length(akeys(feature_value), 1) = 3
);
This will ensure that every data in feature_value could contain exactly three keys: size, format and quality; and won't allow empty data.
Note, that before applying this query, you need to remove all invalid data from the table, or you would receive an error:
ERROR: check constraint "restricted_keys" is violated by some row
You could execute this query in DB console, or since you're using Django, it would be more appropriate to create a migration and apply this query using RunSQL: create an emtpy migration and pass above query into migrations.RunSQL, and pass this query into reverse_sql param for removing the constraint when the migration is unapplied:
ALTER TABLE your_feature_table
DROP CONSTRAINT restricted_keys;
After applying:
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4')
1 row affected in 18ms
sql> INSERT INTO your_feature_table (feature_value) VALUES ('format => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("format"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ().
sql> INSERT INTO your_feature_table (feature_value) VALUES ('a => 124, b => great, c => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("a"=>"124", "b"=>"great", "c"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4, incorrect_key => error')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("size"=>"124", "format"=>"A4", "quality"=>"great", "incorrect_ke...).
I have a table named Products in which there is a column id. It has foreign key relationship with prtyID column in ProductTypes Table. I just want to change the column id of Products table to prtyID. How is it possible? Is there any doctrine command is available for that? Please help me to fix this..
I'm not sure what you are trying to do here... id should be the primary id of Products, not a foreign key for another table. Please add your code if you ask a question.
Usually, Doctrine will use the property name to create the table column. So changing the property name to $prtyId would change your table column as well.
You can give every column the attribute "name" in the annotation of your entity, which will change the column name in your database:
/**
* #ORM\Column(type="integer", name="prtyID")
**/
protected $id;
Or, because you don't define the foreign keys yourself in Doctrine but the association, you can define the association like this:
/**
* #ORM\ManyToOne(targetEntity="ProductTypes")
* #ORM\JoinColumn(name="prtyID", referencedColumnName="id")
*/
protected $type;
This will create the column "prtyID" in your products table which is defined as the foreign key to productTypes primary colum "id"