在 Laravel 8.0 使用 ORM 實現外鍵的自我參考

前言

本文以一個使用者可以有多項任務(Task),一項任務可以有多項子任務為例。

做法

新增 Task 模型的資料表:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use App\Models\Group;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignIdFor(Group::class)->nullable()->constrained()->onDelete('cascade');
$table->foreignIdFor(User::class)->constrained()->onDelete('cascade');
$table->foreignId('parent_id')->nullable()->constrained('tasks')->onDelete('cascade');
$table->timestamps();
});
}

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

修改 User 模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;

// ...

// 找出隸屬於使用者的任務
public function tasks()
{
return $this->hasMany(Task::class)->whereNull('parent_id');
}
}

新增 Task 模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
use HasFactory;

// 找出隸屬於任務的子任務
public function tasks()
{
return $this->hasMany(Task::class, 'parent_id');
}
}

找出使用者所有的任務,以及任務的子任務:

1
2
3
User::query()->with([
'tasks.tasks',
])->first();