Skip to content

Association

JP Barbosa edited this page Jul 23, 2015 · 2 revisions

Association

Generate basic model and migration for authors
php artisan make:model Author --migration
Add custom fields and associations to migration up
nano database/migrations/*create_authors_table.php
    ...
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->timestamps();
        });

        Schema::table('articles', function (Blueprint $table) {
            $table->integer('author_id')->unsigned()->index()->default(1);
            $table->foreign('author_id')
                ->references('id')
                ->on('authors');
        });
    }
    ...
Migrate database
php artisan migrate
Add mass assign fields and get method for articles
nano app/Author.php
...
class Author extends Model
{
    protected $fillable = ['name', 'email'];

    public function articles()
    {
        return $this->hasMany('App\Article');
    }
}
Add author_id to mass assign on articles model and add get author
nano app/Article.php
class Article extends Model
{
    protected $fillable = ['title', 'content', 'author_id'];

    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}
Open console
php artisan tinker
Create author
$author = App\Author::create(['name' => 'Author Name', 'email' => 'email@domain.local']);
Add author to existing article
$article = App\Article::first();
$article->update(['author_id' => $author->id]);
Update all articles to have a existing author
App\Article::query()->update(['author_id' => App\Author::first()->id]);
Add association to Git
git add .
git commit -m "Add authors associations"
Clone this wiki locally