瀏覽代碼

Lesson 7: Eloquent intro.

Frederic G. MARAND 7 年之前
父節點
當前提交
fdfb5b8e62
共有 3 個文件被更改,包括 40 次插入4 次删除
  1. 31 0
      app/Task.php
  2. 3 2
      database/migrations/2017_08_30_195347_create_tasks_table.php
  3. 6 2
      routes/web.php

+ 31 - 0
app/Task.php

@@ -0,0 +1,31 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+class Task extends Model
+{
+    /**
+     * Returns a collection, so cannot be chained.
+     *
+     * @return \Illuminate\Database\Eloquent\Collection|static[]
+     */
+    public static function incomplete_v0()
+    {
+        return static::where('completed', 0)->get();
+    }
+
+    /**
+     * Will answer to Task::incomplete() too but know it is a query scope.
+     *
+     * @param $query
+     *   The existing query.
+     *
+     * @return mixed
+     */
+    public function scopeIncomplete($query)
+    {
+        return $query->where('completed', 0);
+    }
+}

+ 3 - 2
database/migrations/2017_08_29_193342_create_tasks_table.php → database/migrations/2017_08_30_195347_create_tasks_table.php

@@ -15,8 +15,9 @@ class CreateTasksTable extends Migration
     {
         Schema::create('tasks', function (Blueprint $table) {
             $table->increments('id');
-            $table->integer('user_id');
-            $table->text('body');
+            $table->string('body');
+            $table->boolean('completed')
+                ->default(false);
             $table->timestamps();
         });
     }

+ 6 - 2
routes/web.php

@@ -11,9 +11,12 @@
 |
 */
 
+use App\Task;
+
 Route::get('/tasks', function () {
     $name = 'Fred';
-    $tasks = DB::table('tasks')->get();
+    // $tasks = DB::table('tasks')->get();
+    $tasks = Task::all();
 
     // Return a JSON response from the serialized results.
     // return $tasks;
@@ -22,7 +25,8 @@ Route::get('/tasks', function () {
 });
 
 Route::get('/tasks/{task}', function ($id) {
-  $task = DB::table('tasks')->find($id);
+  // $task = DB::table('tasks')->find($id);
+    $task = Task::find($id);
 
   // Return a JSON response from the serialized results.
   // return $tasks;