📌  相关文章
📜  制作完整的 laravel 模型(带有迁移、控制器和资源) (1)

📅  最后修改于: 2023-12-03 15:36:57.545000             🧑  作者: Mango

制作完整的 Laravel 模型(带有迁移、控制器和资源)

在 Laravel 中制作模型非常容易,本文将介绍如何在 Laravel 中创建一个完整的模型,包括迁移、控制器和资源。

步骤
1. 创建数据库迁移

第一步是创建数据库迁移。迁移是一个用于创建表、更新表及其列等的脚本。我们将使用 Artisan 命令行工具来创建迁移文件。

php artisan make:migration create_products_table

这将在 database/migrations 目录下创建一个新的迁移文件。在该文件中,您可以定义要创建的表的列。

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('description')->nullable();
            $table->decimal('price', 8, 2);
            $table->unsignedInteger('stock');
            $table->timestamps();
        });
    }

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

这个迁移文件将创建一个名为 products 的表,该表具有以下列:

  • id 作为自动递增的主键。
  • name 用于产品名称的字符串列。
  • description 用于产品描述的文本列。
  • price 用于产品价格的十进制列。
  • stock 用于产品库存的无符号整数列。
  • created_atupdated_at 分别为创建时间和更新时间的时间戳列。
2. 运行数据库迁移

第二步是运行数据库迁移。这将创建实际的数据库表。

php artisan migrate

这将运行在 database/migrations 目录下的所有迁移文件。

3. 创建模型

接下来,我们需要创建模型。模型是 ORM(对象关系映射)的核心,它代表了数据表的一行或多行。

php artisan make:model Product

app/ 目录下创建模型文件。

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //
}
4. 创建资源

现在我们需要为模型创建一组资源,用于呈现模型的 JSON 表示形式。

php artisan make:resource ProductResource

app/Http/Resources/ 目录下创建资源文件。

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'price' => $this->price,
            'stock' => $this->stock,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
5. 创建控制器

现在我们需要创建控制器来处理请求。

php artisan make:controller ProductController --resource

app/Http/Controllers/ 目录下创建控制器文件。通过使用 --resource 选项创建一个资源控制器,这样它就可以处理 indexcreatestoreshoweditupdatedestroy 这些动作。 修改方法如下:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;
use App\Http\Resources\ProductResource;
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return ProductResource::collection(Product::all());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $product = Product::create($request->all());

        return new ProductResource($product);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return new ProductResource(Product::find($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $product = Product::find($id);
        $product->update($request->all());

        return new ProductResource($product);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $product = Product::find($id);
        $product->delete();

        return response()->json(null, 204);
    }
}

上述控制器方法分别用于:

  • index 用于列出所有产品。
  • store 用于在数据库中创建新产品记录。
  • show 用于显示单个产品。
  • update 用于更新现有产品记录。
  • destroy 用于删除现有产品记录。
6. 添加路由

现在我们需要为控制器添加路由。

打开 routes/web.php 文件,在文件末尾添加以下路由:

Route::resource('products', 'ProductController');

这将为 ProductController 中所有基于资源的路由添加前缀 products。 基于资源的路由包括 indexcreatestoreshoweditupdatedestroy

完成后,使用以下命令启动应用程序:

php artisan serve

现在您可以通过访问 /products 路由和其他基本资源路由来测试该模型的所有功能。