Relaciones uno a muchos (One To Many)

Tenemos ya un modelo Usuarios ya creado.

Creamos el modelo Categoria y su migración:
php artisan make:model Categoria -m
En esa nueva migration:
Schema::create('categorias', function (Blueprint $table) {
   $table->id();
   $table->string('name',50);
   $table->timestamps();
});

   Creamos el modelo Post y su migración:
php artisan make:model Post -m
En la migration:
Schema::create('posts', function (Blueprint $table) {
   $table->id();
   $table->string('name', 200);
   $table->text('body');
   $table->unsignedBigInteger('user_id')->nullable();
   // si se elimina el usuario q no se borren sus posts
   // simplemente q ponga el campo user_id a null
   $table->foreign('user_id')->references('id')->on('users')
     ->onDelete('set null');
   $table->unsignedBigInteger('categoria_id')->nullable();
   // si se elimina la categoria q no se borren sus posts
   // simplemente q ponga el campo categoria_id a null
   $table->foreign('categoria_id')->references('id')->on('categorias')
     ->onDelete('set null');
   // Si quisieramos que al eliminar el user o la categoria se eliminasen
  // todos los posts entonces seria onDelete('cascade')
   $table->timestamps();
});

Creamos el modelo Video y su migración:
php artisan make:model Video -m
En la migration:
Schema::create('videos', function (Blueprint $table) {
   $table->id();
   $table->string('name',50);
   $table->string('descripcion',200);
   $table->string('url',255);
   $table->unsignedBigInteger('user_id')->nullable()
   $table->foreign('user_id')->references('id')->on('users')
     ->onDelete('set null');
   $table->timestamps();
});

En el modelo User.php:
// relación uno a muchos
public function posts() {
   return $this->hasMany('App\Models\Post');
}

En el modelo Categoria.php:
public function posts() {
   return $this->hasMany('App\Models\Post');
}

En el modelo Post.php:
// Relación uno a muchos (inversa)
public function user() { // un post en concreto solo puede haber sido escrito por un único user
   return $this->belongsTo('App\Models\User');
}

// Relación uno a muchos (inversa)
public function categoria() { // un post en concreto solo puede pertenecer a una única categoria
   return $this->belongsTo('App\Models\Categoria');
}

En el modelo Video.php:
// Relacion uno a mucho (inversa)
public function user() { // solo un único usuario puede subir un vídeo en concreto
   return $this->belongsTo('App\Models\User');
}

Ejecutamos todas las migraciones:
php artisan migrate
Suponemos que tenemos ya datos en todas esas tablas para probarlo abrir consola de Tinker:
php artisan tinker
En tinker:
use App\Models\User;
$user = User::find(1
$user->posts;

use App\Models\Categoria;
$cat = Categoria::find(1);
$cat->posts;

exit;

No hay comentarios:

Publicar un comentario