Praleisti ir pereiti prie pagrindinio turinio

Laravel: model, migration, relationship

Sukuriame modelį Post:

php artisan make:model Post -m




Turime migracijos failą database/migrations/data_create_posts_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}:


Ir modelio failą app/Post.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Papildome mogracijos failą:
....
 public function up()
 {
  Schema::create('posts', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('user_id')->unsigned(); //sveikas teigiamas vartotojo id kuris parase posta
   $table->string('body', 140); //posto turinys 140 simboliu max
   $table->timestamps();
            
   //ryšys - ant user_id ir id iš users lentelės, pašalinti istrinus useri ir jo žinutes.
   $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
   });
  }
....

info: https://laravel.com/docs/5.6/migrations#creating-tables

sukuriame lentelė - migruojame:
php artisan migrate

Rezultatas:




Pridedame ryšy app/User.php modelis gali turėti kelis Post modelius:
....
public function posts(){
        return $this->hasMany(Post::class);
    }
....

 "one-to-many" relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model
https://laravel.com/docs/5.6/eloquent-relationships

Kitas ryšys app/Post.php  (leidžiame User modeliui pasiekti Post modelį):
....
class Post extends Model
{
    protected $fillable = ['body'];
    public function user(){
    return $this->belongsTo(User::class);
    }
}
......

Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasManyrelationship, define a relationship function on the child model which calls the belongsTo method:
https://laravel.com/docs/5.6/eloquent-relationships

Komentarai