10장 엘로퀀트 ORM
10.1. 일대다 관계
$ php artisan make:migration create_articles_table --create=articles
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('title');
$table->text('content');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('articles');
}
}
10.1.1. 관계 연결
$ php artisan make:model Article
class Article extends Model
{
protected $fillable = ['title', 'content'];
public function user()
{
return $this->belongsTo(User::class);
}
}
class User extends Authenticatable
{
public function articles()
{
return $this->hasMany(Article::class);
}
}
10.1.2. 관계 확인
$ php artisan tinker
>>> App\User::find(1)->articles()->create([
... 'title' => 'First article',
... 'content' => 'First content',
... ]);
>>> App\User::find(1)->articles()->get();
>>> App\Article::find(1)->user()->first();
10.2. 다대다 관계 연결
$ php artisan make:migration create_tags_table --create=tags
$ php artisan make:migration create_article_tag_table --create=article_tag
class CreateTagsTable extends Migration
{
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->index();
$table->timestamps();
});
}
public function down()
{
Schema::drop('tags');
}
}
class CreateArticleTagTable extends Migration
{
public function up()
{
Schema::create('article_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('article_tag');
}
}
10.2.1. 관계 연결
$ php artisan make:model Tag
class Tag extends Model
{
protected $fillable = ['name', 'slug'];
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
class Article extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
10.2.2. 관계 확인
$ php artisan tinker
>>> App\Tag::create([
'name' => 'Foo',
'slug' => 'foo',
]);
>>> App\Tag::create([
'name' => 'Bar',
'slug' => 'bar',
]);
>>> App\Tag::all();
>>> App\User::find(2)->articles()->create([
'title' => 'Second article',
'content' => 'Second content',
]);
>>> App\Article::all();
>>> $article = App\Article::find(1);
>>> $article->tags()->sync([1,2]);
>>> $article->tags->pluck('name', 'id');
>>> $article = App\Article::find(2);
>>> $article->tags()->sync([1]);
>>> $article->tags->pluck('name', 'id');
>>> App\Tag::find(1)->articles;
10.2.3. 다대다 관계 작동 원리
mysql> SELECT * FROM article_tag;
10.3. 마치며
$ git commit -m '엘로퀀트 ORM'
$ git tag 1010-eloquent