Beziehungen / Foreign Key Constraints

Laravel Eloquent ist der Query Builder von Laravel, der es ermöglicht z.B. alle Comments zu einem Post mit vereinfachter Syntax anzuzeigen.

Beziehungen zwischen Tabellen werden mit „constraints“ erstellt. Für die Nutzung in Laravel müssen sie zudem in den betreffenden Models definiert werden.

Beziehungen im Model festlegen


app/Models/Post.php
    public function comments()
    {
        return $this->hasMany(Comment::class);
        // note: we can also include comment model like: 'App\Models\Comment'
    }

app/Models/Comment.php
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
Datensätze einfügen
// insert 1 post
$post = new Post();
$post->title = "Test post";
$post->body = "Post body goes here";
$post->save();

// insert 2 comments
$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 1";
$comment->save();

$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 2";
$comment->save();
Datensätze abrufen
// get all comments of a post
$id = 1;
$post = Post::find($id);
$all_comments = $post->comments;
dd($all_comments);

// get the post of a comment
$id = 1;
$comment = Comment::find($id);
$post = $comment->post;
dd($post);

Beziehung in Migration erstellen

Klassische Verknüpfung

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});
// Verknüpfung gem. Konventionen (user_id => Tabelle users)
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});
// Tabellenname selbst festlegen
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
});
// Löschverhalten festlegen
$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')
      ->onDelete('cascade');
// Löschen von Verknüpfungen
$table->dropForeign('posts_user_id_foreign'); // Tabelle, Spalte
$table->dropForeign(['user_id']); // Tabelle automatisch gem. Konvention

// aktivieren/dekativieren der Verknüpfungen
Schema::enableForeignKeyConstraints();
Schema::disableForeignKeyConstraints()

// Column modifiers müssen vor constrained angegeben werden
$table->foreignId('user_id')
->nullable()
->constrained();


Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert