我写了一些整个循环的例子。 laravel 中有约定使用唯一的自动增量“id”,并具有像 RELATION_id 这样的外键。因此,如果您想更改表名和列名,可以按照以下示例进行操作:
类别模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'id',
'name',
];
public function subcategories(){
return $this->hasMany(Subcategory::class, 'category_id', 'id');
}
}
子类别模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
protected $table = 'subcategories';
protected $fillable = [
'id',
'category_id',
'name',
];
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
}
类别表迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
// PRIMARY
$table->bigIncrements('id');
// ADDITIONAL
$table->string('name');
// TIME
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('categories');
}
}
子类别表迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSubcategoriesTable extends Migration
{
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
// PRIMARY
$table->bigIncrements('id');
// FOREIGN
$table->unsignedBigInteger('category_id')->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
// ADDITIONAL
$table->string('name');
// TIME
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('subcategories');
}
}
在控制器中的使用
// 1
public function categories()
{
$categories = Category::all()->get();
return view('categories', [
'categories' => $categories,
]);
}
// 2
public function catsWithSubcats()
{
$cats_with_subcats = Category::with('subcategories')->get();
return view('cats_with_subcats', [
'categories' => $cats_with_subcats,
]);
}
// 3
public function subcatsWithCats()
{
$subcats_with_cats = Subcategory::with('category')->get();
return view('subcats_with_cats', [
'subcategories' => $subcats_with_cats,
]);
}
如果您想在刀片中显示所有类别及其子类别,则无需使用第 2 或第 3 方法,只需使用第 1 方法。在“resources/views/...”中创建“categories.blade.php”并在其中写下如下内容:
@foreach($categories as $category)
@foreach($category->subcategories as $subcategory)
<p>{{ $subcategory->name }}</p>
@endforeach
@endforeach