To make it clear let's make classic example - User and Post.
Creating db schema in Symfony2 is clean and simple:
we create entities Post and User
additionaly we can simply add columns/indexes to each.
then just add value with OneToMany annotation in User and ManyToOne in Post
..well, that's it. Now if we run db:schema:update --force and we can get what we want - database schema and simple adding another rows in database.
What about Laravel4? So far only solution I found:
create/generate Post and User models
declare in each model which table it refers to
create migrations and in Post migration add foregin key to user_id column
run migration
add in each model methods in which we refer to the other model (hasMany, belongsTo .. )
As I wrote it, it doesn't seem so complicated, but it's not so concentrated in Laravel as it is in Symfony. I'm kinda lazy person and I really enjoy the process in Symfony, while in Laravel it is a little bit too diffuse. Is there any simpler ( lazier :P ) way to do this in Laravel? Something like creating schema based on Model?
The question makes sense but unfortunately there isn't such functionality on Laravel at the moment.
As opposed to running migrations from your models (symfony) you must create the migrations first, the you can use the models to seed database tables if they have foreign keys.
I use the Jeffrey Way Generators https://github.com/JeffreyWay/Laravel-4-Generators
to speed up the process so for example if I have a users table and a profile table (many to many) then I would perform these tasks on command line:
php artisan generate:migration create_users_table --fields="username:string, password:string, email:string"
php artisan generate:migration create_profiles_table --fields="name:string, lastname:string, phone:string"
php artisan migrate
php artisan generate:pivot users profiles
php artisan migrate
Then you can create your models (you can also generate an entire CRUD resource or Scaffold)
php artisan generate:model user
php artisan generate:model profile
Then in your User Model
public function profile()
{
return $this->belongsToMany('Profile');
}
In your Profile Model
public function user()
{
return $this->belongsToMany('User');
}
Yes, there are some plugins / commands that speed up the development.
For example Jeffrey Way's Laravel-4-Generators
Related
Coming from a long Symfony-Doctrine background, I have started learning Laravel 8.
One of my first discovery was that migration needed to be manually created after using make:migration (from what I understood thus far) in both Models and Migration.
Symfony, with Doctrine, allowed a bunch of automatisation, and I only needed to create the field or relation from the Model (php annotation or yaml) - before launching doctrine:schema:validate and make:migration
https://symfony.com/doc/current/doctrine.html#migrations-adding-more-fields.
Let 'say I create a Post and Comment entity, with a One-To-Many relationship.
If I define the relation in the php classes
class Comment extends Model
{
/**
* Get the Post owning this comment
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Post class
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Is possible to generate the migration scripts that would update the database and create these relation ship ? Or will I have to rewrite it twice (once in the PHP class with hasMany/BelongsTo then again in the Migtration file ?
Not having a central file to map/read a model (which linkied php and database) seems weird to me now.
I've only started but the documentation does not seems to mention anything equivalent
Edit : for more clarity : I'm asking if there are equivalent of Generating migration code/script from models (or a central mapping file : yaml or annotation ) without having to write fields to both migration and models ( in $fillable or other fields...)
Edit 2 Closest thing I could find is this
https://github.com/laracasts/Laravel-5-Generators-Extended
Another use case where this is cumbersome : many-to-many migrations
Having to manually write that third middle table from scratch is really something I wish was made automatically.
In laravel framework despite other famous fameworks like symfony or python django, you're responsible for making database migration files. By this way, you are free to customize your database schema and add any database constrains like (unique constrain, relation constrains and etc.). Also you can add any raw sql using \DB::unprepared(); in your migration files.
I can tell you that it is normal to be a little confuse about this flow, because you've used to this kind of automation in other frameworks like I did, but beilieve me, you get to used to this flow.
By the way, there are some packages out there that do this automation (create migration files according to model) for you.
For creating a migration you need to run command
php artisan make:migration migration_name
And for creating a model you need to run command
php artisan make:model table_name
Refer to this link
https://laravel.com/docs/8.x/eloquent#generating-model-classes
By creating a model you create a table, where you can define the columns types and different properties and define the relationship with other tables.
By creating a migration file you can define the table columns and the constraints.
Here are the tables in my scenario
user (user_id)
user1_order
user2_order
user3_order
user1_calcs
user2_calcs
..........
I have my own reasons to have separate table per user (lots of data per user, lots of joins/queries in my app, separation of user data, user satisfaction)
Laravel has migration feature, so you have to create a migration that will create a table..
My question is, how would I use Laravel to my scenario? as I am not sure when user signs up, and I can not pre-generate user tables until a user signs up..
Any help is highly appreciated...
You could use Eloquent Events (do not confuse it with Laravel Events) to run table creation tasks, for example you could run custom artisan command directly from your code.
This command could create migrations from prepared stubs and then run php artisan migrate command.
I usually work with SF2, and with Doctrine, Entities can be generated automatically and if you build the schema in a Soft like MySQL Workbench you can do Reverse Engineering.
I'm new to Laravel so there is a way to do these both things? I would use Laravel because I've to do a very little project, but I didn't want to write all this code for what we call "Migrations", seems very boring no?
So there is a way to generate this stuff in laravel? Maybe I've to use Doctrine in Laravel for that?
If you want to generate migration files from an existing mysql database you can use a Laravel package called XCMer / larry-four-generator. Apart from reverse engineering it has a bunch of other features.
Larry Four is a Laravel 4 package offering advanced model and
migration generation functionality. Thanks to Larry you can quickly
jot down the data scheme for your idea in an easy DSL and genereate
migrations and models from it with just a single click. Larry can also
analyse your existing data scheme and generate some magic for you too.
Try the original best master branch
https://github.com/XCMer/larry-four-generator/tree/master
or my Extended Models fork offering additional functionality
https://github.com/XCMer/larry-four-generator/tree/Gadoma-extendedmodels
As far as I can tell there is still no way to reverse a schema to migration files, using Laravel only. But you can:
1) Export your MySQL schema
mysqldump -u root -p --no-data dbname > schema.sql
2) Create a migration to use your schema
php artisan migration:make create_schema
3) Boot your full schema
class CreateSchema extends Migration {
public function up()
{
$file = file_get_contents(app_path().'/database/data/full_schema.sql', true);
DB::unprepared($file);
}
public function down()
{
}
}
4) After that, if you need to do any changes to your schema, just create new migrations and make your changes.
Not tested, but should work.
Im trying to add fields to the Users model that is based around Sentry 2 for Laravel 4.
I want to do it properly with migrations.
Is there a way to simply add to the sentry 2 migrations? or should i simply make my own migrations and add the required extra fields?
any guidance with the framework would be awesome!
If you want add some fields you need this:
run Sentry Migrations: php artisan migrate --package=cartalyst/sentry
create a migration to add custom fields to Users table: php artisan migrate:make --table=users
example in funcion up():
Schema::table('users', function(Blueprint $table)
{
$table->string('new_field');
});
And then extend the Sentry User Model:
Check this example is extending Sentry Model and full implementation example check this: Laravel 4 Backend and simple web site
The purpose of migrations is versioning of the database structure. The answer to any question similar to "where should I put database changes?" is always: "in a new migration", because then you're able to rollback changes.
In this case, I think I would first add Sentry 2 to your project and commit "Added Sentry 2". After, I would create a new migration with your desired changes, then commit: "Added fields x y and z to Users table".
See also the introduction paragraph of the documentation: http://four.laravel.com/docs/migrations
The best way to do this is simple navigate to the actual sentry migration file found at
vendor/cartalyst/sentry/src/migrations
copy the needed migrations out and create your own migrations file.
There is no other way. Just me being lazy i guess.
I am totally new to FuelPHP, ORM and migrations in general so sorry if I come across like a newbie, but I've been struggling with this for a few hours now so I thought I'd ask for help. I think I'm either doing something wrong or missing something fundamental.
I am trying to create a users model, for simplicity let's say it just has a string representing name.
I was under the impression that using the following two Oil commands would create a users model, and an associated migration which after running would build an associated table:
php oil generate model user name:string
oil refine migrate
This does successfully create the model and migration, but running the second command doesn't build the table in the database.
If I run these commands on the other hand:
php oil generate migration create_user name:text
oil refine migrate
The migration is created and the table is built in my database. I noticed that perpending 'create_' to the migration name made it possible to create the table, whereas leaving it off (i.e php oil generate migration user name:text) doesn't insert the table to the DB. I noticed the generated migrations with and without the 'create_' are significantly different.
So my question ultimately is, how do I create the model, associated migration which creates the table? Or, am I totally misunderstanding something?
Thanks!
If you get 'Already on the latest migration', your migration tracking data is out of sync. Migrations are tracked both in the database (a table called migration) and a config file in your environment folder called migrations.php.
If there is already an entry in one of them, oil will not run it again.
So you can't just delete the table through the backdoor and then run the migration again. You'll have to run a 'migrate:down' to revert the last migration, or if you delete all, also delete the migration table and config file.
Again, credit to Harro Verton on the FuelPHP forums.