简体   繁体   中英

Building database schema Laravel4 vs Symfony2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM