Laravel - Seeding strategy for tables with foreign keys - laravel

I have an application that I want to port over to Laravel.
It already has data so I would need to port and set the database data using Migration and Seeding.
In my app, I have Table foo and Table bar. A field in Table bar is a foreign key to a field in Table foo.
When I seed, the id's inserted would most likely be different from the old application.
The problem then is that the integrity of the foreign key fields would be compromised since the ids' would be different.
Is there any strategy to solve this issue? I don't mind changing the values of the foreign key fields as long as it points to the correct row.

Does not depend of the language or framework, Laravel, Rails... the logic stays same.
You have to do some smarts select on bar table to be able to link foo to bar.
So in Laravel context you open FooTableSeeder.php and write something like this:
$bar1 = Bar::where( ---your condition---)->first();
$bar2 = Bar::where( ---your condition---)->first();
DB::table('foo')->truncate();
$foogees = array(
array( 'bar_id' => $bar1->id ...),
array( 'bar_id' => $bar1->id ...),
array( 'bar_id' => $bar2->id ...),
...
);
DB::table('foo')->insert($foogees);

I had a similar situation. My solution was to manually input the foo id's. It worked well for me.
Normally, I wouldn't recommend setting the primary keys for a table, but since you're porting it, I think this is one of those situations where it would be acceptable.

Related

Backpack Laravel select2_from_ajax field returns results, but I can't select any

I'm implementing a 'select2_from_ajax' field using Backpack for Laravel.
I've implemented this in other places and it works correctly. But for some reason when implementing it this time it will not let me select any of the options and doesn't show the highlight when mousing over the options. It lists out the options correctly, I just can't select any of them.
The only thing I can think of is that the relationship it's trying to reference doesn't have a primary 'id' field in the database, but I'm not sure why that would affect this.
I have implemented both the index and show routes.
The issue was that the relationship field's primary key was not 'id' it was setup with a different column name.
I reworked the data structure so the foreign key referenced was pointing to a column labeled 'id'.

is bad habit to don't use foreign in migration laravel?

I am new in laravel. In my tutorial video teacher use foreign in migration but,i can create my relationships without it and use just belongTo and hasMany.When i use foreign can not delete one post easily (error is you can not delete because parent foreign has child ......).
my question is my way is good or not? and why?
Thank you all
Your way is good but I think foreign keys are better. Had you not had that foreign key, you would have deleted the post but all that post's children (referred to as orphans because they no longer have a parent) would have stuck around. In order to get around the foreign key error, you would need to first delete all the children for that post, and then delete the post.
The good news is foreign keys can also do this for you so you don't need to worry about keeping track of all the children. When you setup the foreign key, if you add the on delete cascade clause, when deleting the post, the database would automatically remove all of the posts's children for you and deleting a post without first deleting the children would no longer result in an error.
If it's your preference to keep the children around even when the post is deleted, you can use on delete set null instead which would simply set the children's foreign key to null rather than delete the record.
This is all useful for enforcing data integrity (databases should contain only accurate and valid data).
The answer really is not 'is this good practice in Laravel' so much as 'is this good practice for database management'.
There are many articles on the topic as to the good and bad side of using foreign keys. Here is a good explanation on the DBA stack exchange
https://dba.stackexchange.com/questions/168590/not-using-foreign-key-constraints-in-real-practice-is-it-ok
My personal preference is to use them to maintain data integrity. The real power comes in adding cascading deletes to the relationship (if applicable to your design).
It really comes down to how good you want your database to be.The main reasons to use foreign keys in your database are
To prevent actions that would destroy links between your tables
This would prevent the invalid data from being inserted to the foreign key column as it has to point to a existing value
Also defining foreign keys makes your query faster depending on database I don't know the exact milliseconds but if I find it out I will post it.
Well from the laravel point of view the way you do is a better way as this is how one of the main teacher of the Laravel(Jeffrey Way) teaches in the getting started with laravel series.
Foreign Keys are the way to define relationship between tables in your database whereas Laravel belongsTo() or hasMany() is a way to define relationship between tables in Laravel

Foreign key, or no foreign key? Defining Laravel relationships

What is the difference between defining a foreign key VS just creating an integer column named user_id?
// create_posts migrations
$table->integer('user_id')->unsigned();
// vs
$table->foreign('user_id')->references('id')->on('users');
Can they be used interchangeably? What purpose do each one serve? Which is considered a best practice, first or second definition?
Edit
The command $post->user() will work either ways, so what advantages does usage of a foreign key bring?
$table->integer('user_id')->unsigned();
// Above command is creating a column in database and it is required to have the required table structure
$table->foreign('user_id')->references('id')->on('users');
// Above command is creating foreign key index and making reference to id in users table.
As you can see from command explanations they can't be interchangeable, you need first command to have second command without first second command would complain.
Best practise is to use both of them together.
Few of advantages are listed below:
You can implement cascade update/delete.
Database level validation that only valid values of user_id is recorded ( to avoid some one entering 999999 which might be invalid or non existing user_id).
Above two are main advantages and you can express multiple scenarios how above two can be life saviour.
Let's say in post table by human error or bug in script makers user_id = 9999. What you think $post->user() will do?
Unless you can have a post without any reference to user you can see there could be multiple logical issue you may find if foreign keys are not used.
Think of foreign keys as enforcing relations and taking care of post if user is removed / deleted from db.
No, They can't be used interchangeably and each one has its usage. Use index when you want to define index on column, means database index, see here. But when you define a foreign key it set a index to that column (for searching, ...) and also make a relation between user_id and id column in user table, so if there is a user by id 10, then you can use user_id = 10 on another table. Also it has another benefits such as making sure your data are integrated. For example you can't delete user by id 10 if there is article that belongs to this user. For more information see this.
The first line, will only create a user_id column not something special,
while the other line will create a column as a foreign key which will be tightly coupled with id column of users table, this will create some limitations.
read about foreign key reference
For the best practices I always use:
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
Don't mix the definition of index with foreign key, they don't mean the same.

Kendo UI Foreign Key

I am new to Kendo UI and I got this problem. I don't understand, what are the basic steps in showing child object information in a column with a foreign key property. I mean, what do I have to do to create a foreign key column. It might be a silly question, but I saw a demo of foreign key on demos pages http://demos.telerik.com/kendo-ui/web/grid/foreignkeycolumn.html, still, I didn't quite get how does it work.
Thanks,
Vidmantas
Below is the MVC example for foreign key column demo:
Its as simple as it sounds,
For example, lets say you have CoachId field in a table and its the foreign key of the table
Coach that has CoachId and Name columns. Now you wish to present the Coach Name instead of the CoachId in the Grid.
columns.ForeignKey(student => student.CoachId,
(System.Collections.IEnumerable)ViewBag.Coaches, "CoachId", "Name")
.Title("Coach");
Then from the controller or from Code you have to send all the coach records in Viewbag or Viewdata.
Cheers!!

Slickgrid/Dataview without Primary Key

I am using SlickGrid/DataView for CRUD purposes. It is working fine. However, we have some of the tables which do not have primary key.
Q1: How can I use dataview for such tables? If not then am I left with using Slickgrid without dataview only OR I have another choice? Any example would be appreciated.
Q2: Does Dataview support composite primary keys? If yes, can anybody give me an example of using it?
thanks
SlickGrid requires at least the ID field, you can take whichever that could be named differently in your table and then alias it to "ID" but it has to be a UNIQUE id field because SlickGrid is using it for row naming and so on.
If you do not have a UNIQUE field and you really want to use composite primary keys, then I suggest you create a fake ID field which you simply increment by 1 each loop. A simple way is to do this while fetching the data, something similar to the following:
$sqlTable = "SELECT * FROM myTable";
$result = mysql_query($sqlTable,$connMySQL);
$i = 1;
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$tabData[] = array(
"id" => $i++,
"column1" => $row['column1'],
"column2" => $row['column2']
);
}
Now if you do use a fake ID like I just said, this will give you some problems doing the CRUD (update, delete) since your ID is not real and point to nowhere... but there is a way to fix that too. By the way, you should split your question into 2 separate question since they are different subjects. I suggest you ask your CRUD subject in another question and that you provide some code so we can develop from there.

Resources