Eloquent Relationship without defining foreign key constraint - php

I have some query related to Eloquent Relationships in Laravel.
If I didn't specify a foreign key when using any relationship defined by laravel so laravel makes it work by assuming the foreign key based upon the parent model name as written in laravel 8 documentation.
So what I want to ask is that if laravel is only assuming means laravel will make the relationship work but data consistency will not be maintained by laravel as what foreign key does? Am I right?
And if I am right then the solution will be to explicitly define the foreign key in migration file when using relationships?

I guess, you're mixing two things, the database's DDL/schema and the ORM/database abstraction layer:
The database's DDL/schema defines, how the database itself is structured and works. In Laravel, this can be controlled via migrations.
The ORM/database abstraction layer normally doesn't alter the schema, it just does CRUD (which is DML not DDL). In Laravel, this can be done with either the query builder or Eloquent, which is an ORM.
That means, the former creates the foreign key constraints, the latter only assumes a column name to put in the SQL query it creates

Related

Laravel MYSQL Foriegn Key

While designing the database for a laravel software using MYSQL, is assigning foreign keys relevant or does Laravel take care of that "Software side".
In the migration we have something like
Table Example:
$table->unsignedBigInteger('user_id');
should i modify the example table in phpmyadmin and make user_id a foreign key? is there a better way or is this not relevant or necessary?
You should define foreign key constraints in your migration. When using code base you should make all the changes using migrations.
Additionally by defining foreign key you actually build a relation between 2 tables otherwise this relation will be at code level. When relation is built database will restrict to have only values which actually exists in main table. Using foreign key you can also do cascading (on update and delete) at db level.
Reference what are the advantages of defining a foreign key
Why should I use foreign keys in database?
if use Laravel 7 ,you can use this short that is a column name user_id foreign to ID user in the table users :
$table->foreignId('user_id')->nullable()->constrained()->onDelete('cascade');

How to stop Doctrine2 Migrations:Diff from always adding foreign key relationships that already exist in Database?

I'm using doctrine2 with a symfony2.1 project. I have an entity that has a few many to one relationships to other tables. The foreign key relationships for these many-to-one's have already been updated in the database, but every time I run migrations:diff or schema:update --dump-sql it adds the same update commands to add the foreign key relationships again. When I run schema:validate it says my mapping is out of sync with my database.
My application works fine, the relationships are working properly, and the schema in my database looks correct. Why is doctrine still trying to add these foreign keys?
Here's my code (for one of the problematic parameters):
In my "Ticket" entity I have:
/**
* Authenticated User who scored the ticket.
*
* #ORM\ManyToOne(targetEntity="CS\SecurityBundle\Entity\User")
* #ORM\JoinColumn(name="scoring_user_id", referencedColumnName="id")
*/
protected $scoringUser;
I currently have it set up to be one-directional, so there is no inversedBy in the User entity.
This generates the following in my migrations or schema:update dump even though it's in the database already:
$this->addSql("ALTER TABLE tickets ADD CONSTRAINT FK_54469DF4BB0D9452 FOREIGN KEY (scoring_user_id) REFERENCES users (id)");
Any idea what I'm doing wrong here?
Why is doctrine still trying to add these foreign keys?
The correct term here is "foreign key constraint". Without the constraint, the column in question is just a column. It's the constraint that enforces that the value of that column exists as a primary key in another table.
Why is doctrine still trying to add these foreign keys?
Because the database vendor/engine doesn't support foreign key constraints, but Doctrine fails to recognize that.
If I have to guess, you're using MySQL with the MyISAM engine. MyISAM doesn't support foreign key constraints. Unfortunately Doctrine isn't "smart" enough to see that. It sees that MySQL is used, therefor blindly assumes that foreign key constraints are supported.
My advise is to switch to the InnoDB engine, unless you have a good reason for using MyISAM.
ALTER TABLE table_name ENGINE=InnoDB;
Converting Tables from MyISAM to InnoDB

Does Doctrine 2 required foreign keys to be defined?

I have a relational database, however, there aren't any foreign keys defined, and many of the tables are not InnoDB, so can't support foreign keys anyway.
I would like to start experimenting with Doctrine on this database, but there is a lot of reference to foreign keys in the documentation, so I'm not sure if this is possible.
I'm anxious about diving in and changing table storage engines to InnoDB and defining tons of foreign keys, because I don't want to impact performance if I don't have to.
Does Doctrine require foreign keys to be defined in order to manage associations between entities?
If it isn't required but optional, what features of Doctrine do I sacrifice if I don't have foreign keys defined?
There is no reason for you to switch to InnoDB for Doctrine.
No.
I find the Doctrine's CLI tools for updating and generating the database schema will often try to generate the SQL with foreign keys. You can manually set up the database, or modify the code it generates, to avoid this.
So, no, it is not a problem.
If you define some Associations mapping for your entities it may convert to foreign keys by doctrine automatically
http://docs.doctrine-project.org/en/latest/reference/association-mapping.html
i you want those foreign keys in your db too you have to use doctrine CLI for creating your schema
for more info about using doctrine cli :
http://docs.doctrine-project.org/en/latest/reference/tools.html

Query sharepoint table

I am using cakePhp to query a MSSQL table from Sharepoint. I have no control over the column names, so I cannot create an auto-incremented 'id' for the PK.
I would like to query the table via my 'Users' controller (which already has its own model). Could someone please guide me in the right direction?
Unfortunately, CakePHP does not support composite primary keys. They usual workaround (add a new column with a simple, singular primary key and put a UNQIUE constraint on the columns that used to be the composite key) doesn't work for you either, because you cannot change the schema.
It looks like your hosed. Couple of things you can do:
Get a better ORM or PHP framework. One that does support composite primary keys (E.g. something that uses Doctrine 2). Honestly, CakePHP's ORM isn't that great.
Use raw queries through the CakePHP database layer. You'll still get back nested arrays like you would when using a true CakePHP model. It may be enough for you, depending on what you are trying to achieve.

Zend_Db. Am I required to manually set primary and foreign key when building db table?

As I read J.Gilmore Zend Book (Models section):
class Game extends Zend_Db_Table_Abstract
{
protected $_primary='id'; //line 4
}
[..]Line 4 identifies the table's primary key.By default the framework will
presume the primary key is an automatically incrementing integer named id,so
this line is not necessary [..]
I have a question:
Do I need to manually set primary and foreign key while building a table
(Ex. in phpmyadmin with something like "PRIMARY KEY (id),FOREIGN KEY (post) REFERENCES users (id)
ON DELETE CASCADE")?
Or I can handle tables relationships and fields nature just by referring to Zend code using $_primary,$_dependentTable,$_referenceMap and so on?
thanks
Luca
Both. Although you can get away with an ORM dealing with relations, the database ensures at low-level those relations are respected. Always let the database do its job as much as possible, it is built for handling relations and preventing data corruption. What if your ORM has a bug?
As a somewhat related example, say you have a field declared as int in database, you are responsible as a developper for making sure you use int's in your queries, but the database enforces that rule at a lower level, protecting your data in case you don`t.
You should define the primary/unique keys and any other indexes properly when you create the table.
After you've done this in 99% of cases Zend_Db will understand what's going on as it's able to read the table metadata and derive the primary key from that.

Categories