Sfoglia il codice sorgente

Lesson 18: adding user ids to posts, comments.

Frederic G. MARAND 6 anni fa
parent
commit
11f0e920ea

+ 4 - 0
app/Comment.php

@@ -7,4 +7,8 @@ class Comment extends Model
     public function post() {
         return $this->belongsTo(Post::class);
     }
+
+    public function user() {
+        return $this->belongsTo(User::class);
+    }
 }

+ 20 - 15
app/Post.php

@@ -2,31 +2,36 @@
 
 namespace App;
 
-use Illuminate\Http\Request;
+class Post extends Model
+{
 
-class Post extends Model {
-
-  /**
-   * These fields are OK for mass assignement.
-   *
-   * @var array
-   */
-  protected $fillable = ['body', 'title'];
+    /**
+     * These fields are OK for mass assignement.
+     *
+     * @var array
+     */
+    protected $fillable = ['body', 'title'];
 
     /**
      * @param string $body
      */
-    public function addComment(string $body) {
+    public function addComment(string $body)
+    {
 //      Comment::create([
 //          'body' => $body,
 //          'post_id' => $this->id,
 //      ]);
 
         $this->comments()->create(compact('body'));
-  }
+    }
+
+    public function comments()
+    {
+        return $this->hasMany(Comment::class);
+    }
 
-  public function comments()
-  {
-      return $this->hasMany(Comment::class);
-  }
+    public function user()
+    {
+        return $this->belongsTo(User::class);
+    }
 }

+ 4 - 0
app/User.php

@@ -26,4 +26,8 @@ class User extends Authenticatable
     protected $hidden = [
         'password', 'remember_token',
     ];
+
+    public function posts() {
+        return $this->hasMany(Post::class);
+    }
 }

+ 1 - 0
database/migrations/2017_09_02_084536_create_posts_table.php

@@ -15,6 +15,7 @@ class CreatePostsTable extends Migration
     {
         Schema::create('posts', function (Blueprint $table) {
             $table->increments('id');
+            $table->integer('user_id');
             $table->string('title');
             $table->text('body');
             $table->timestamps();

+ 1 - 0
database/migrations/2017_09_02_190346_create_comments_table.php

@@ -15,6 +15,7 @@ class CreateCommentsTable extends Migration
     {
         Schema::create('comments', function (Blueprint $table) {
             $table->increments('id');
+            $table->integer('user_id');
             $table->integer('post_id');
             $table->string('body');
             $table->timestamps();