Merhaba Yazılarıma etiket sistemi yaptım en azından izlediğim tutorialda yapıyordu fakat ben mantığını anlamadım.
Article Model Bu Şekilde:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function tags(){
return $this->belongsToMany(Tag::class);
}
}
Article Table Şu Şekilde
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('excerpt');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
Tutorialda ilişki için article table ve tags table arası için article_tag table oluşturdu ve şu şekilde gitti:
class CreateTagsTable extends Migration
{
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('article_tag', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('article_id');
$table->unsignedBigInteger('tag_id');
$table->timestamps();
$table->unique(['article_id','tag_id']);
$table->foreign('article_id')->references('id')->on('articles');
$table->foreign('tag_id')->references('id')->on('tags');
});
}
public function down()
{
Schema::dropIfExists('tags');
}
}
Ben php artisan tinker ile terminalde:
$article = App\Article::first() ve $article->tags yazarsam bana article in taglerini getiriyor zaten amaçta o fakat direkt o ara tablo ismi bile geçmiyorken işlem nası işliyor onu anlamadım en azından bu tablonun şu sutünu ile diğerini şu sutünü eşleşip o satır geliyor diyemiyorum o arada ki article_tag tablosu nasıl kullanıldı anlamadım kısacası yardımcı olursanız çok sevinirim.
Ve
$article = App\Article::first()
$article->tags
=> Illuminate\Database\Eloquent\Collection {#4196
all: [
App\Tag {#3581
id: 1,
name: "laravel",
created_at: "2020-10-28 17:38:36",
updated_at: "2020-10-28 17:38:36",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4204
article_id: 1,
tag_id: 1,
},
},
App\Tag {#3258
id: 2,
name: "php",
created_at: "2020-10-28 17:38:44",
updated_at: "2020-10-28 17:38:44",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#4144
article_id: 1,
tag_id: 2,
},
},
Ve buradaki pivot dediği ne anlama geliyor ?