You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中Eloquent ORM是什么?求项目实现示例

Hey there! I get that wrapping your head around Eloquent can feel overwhelming when you're just starting out with Laravel. Let's walk through super simple, practical examples that you can copy-paste into your project and tweak as needed.

Basic Eloquent ORM Implementation Examples

1. Create a Model & Database Migration

Eloquent models map directly to your database tables. Let's start with a Post model (for blog posts):

First, run this Artisan command to generate a model and a corresponding migration file:

php artisan make:model Post -m

Update the Migration File

Open the migration file (found in database/migrations/) and add fields to the up() method:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Run the migration to create the posts table:

php artisan migrate

Configure the Model

Open app/Models/Post.php and set the $fillable property (to allow mass assignment of fields):

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Allow these fields to be set via mass assignment
    protected $fillable = ['title', 'content'];
}

2. Basic CRUD Operations

Here's how to perform core database actions with Eloquent:

Create a Record

// Option 1: Instantiate and save
$post = new \App\Models\Post();
$post->title = 'My First Eloquent Post';
$post->content = 'This is way easier than writing raw SQL!';
$post->save();

// Option 2: Use the create() method (requires $fillable)
$post = \App\Models\Post::create([
    'title' => 'Another Quick Post',
    'content' => 'Using the create shortcut'
]);

Read Records

// Get all posts
$allPosts = \App\Models\Post::all();

// Get a single post by ID
$singlePost = \App\Models\Post::find(1);

// Filter posts with a condition
$filteredPosts = \App\Models\Post::where('title', 'like', '%First%')->get();

Update a Record

// Find and update
$post = \App\Models\Post::find(1);
$post->title = 'Updated: My First Eloquent Post';
$post->save();

// Update directly via query
\App\Models\Post::where('id', 1)->update(['content' => 'Updated content here']);

Delete a Record

// Find and delete
$post = \App\Models\Post::find(1);
$post->delete();

// Delete directly by ID
\App\Models\Post::destroy(1);

3. Simple Relationship Example (One-to-Many)

Let's add a Comment model to show how Eloquent handles relationships (a post can have many comments):

  1. Generate the Comment model and migration:
php artisan make:model Comment -m
  1. Update the Comment migration to add a post_id foreign key:
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->onDelete('cascade');
        $table->text('body');
        $table->timestamps();
    });
}
  1. Run the migration:
php artisan migrate
  1. Define relationships in the models:
  • In Post.php:
public function comments()
{
    return $this->hasMany(\App\Models\Comment::class);
}
  • In Comment.php:
protected $fillable = ['body'];

public function post()
{
    return $this->belongsTo(\App\Models\Post::class);
}
  1. Use the relationships:
// Get all comments for a post
$post = \App\Models\Post::find(1);
$comments = $post->comments;

// Create a comment linked to a post
$post->comments()->create([
    'body' => 'Great post, thanks for sharing!'
]);

// Get the post that a comment belongs to
$comment = \App\Models\Comment::find(1);
$parentPost = $comment->post;

Start with these basics, and you'll get comfortable with Eloquent in no time!

内容的提问来源于stack exchange,提问作者faisal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:27:47