>  기사  >  백엔드 개발  >  Laravel 5 기본(7) - Eloquent(laravel의 ORM)

Laravel 5 기본(7) - Eloquent(laravel의 ORM)

WBOY
WBOY원래의
2016-08-08 09:26:51834검색
  • 첫 번째 모델을 생성해 보겠습니다
<code>php artisan make:model Article
#输出
Model created successfully.
Created Migration: 2015_03_28_062517_create_articles_table</code>

생성된 파일 확인app/Article.php

<code><?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model {

	//

}</code>

Model에서 상속받는 것 외에 특별한 것은 없지만 Laravel의 Model에 모두 캡슐화되어 있는 강력한 기능을 가지고 있습니다. 모델은 자동으로 save() update() findXXX()과 같은 강력한 기능을 갖습니다.

  • Tinker는 프로젝트와 상호 작용할 수 있는 laravel에서 제공하는 명령줄 도구입니다.
<code>php artisan tinker

#以下是在tinker中的交互输入
Psy Shell v0.4.1 (PHP 5.4.16 — cli) by Justin Hileman
>>> $name = 'zhang jinglin';
=> "zhang jinglin"

>>> $name
=> "zhang jinglin"

>>> $article = new App\Article;
=> <App\Article #000000005c4b7ee400000000ab91a676> {}

>>> $article->title = 'My First Article';
=> "My First Article"

>>> $article->body = 'Some content...';
=> "Some content..."

>>> $article->published_at = Carbon\Carbon::now();
=> <Carbon\Carbon #000000005c4b7ee600000000ab91dcb6> {
       date: "2015-03-28 06:37:22",
       timezone_type: 3,
       timezone: "UTC"
   }

>>> $article;
=> <App\Article #000000005c4b7ee400000000ab91a676> {
       title: "My First Article",
       body: "Some content...",
       published_at: <Carbon\Carbon #000000005c4b7ee600000000ab91dcb6> {
           date: "2015-03-28 06:37:22",
           timezone_type: 3,
           timezone: "UTC"
       }
   }

>>> $article->toArray();
=> [
       "title"        => "My First Article",
       "body"         => "Some content...",
       "published_at" => <Carbon\Carbon #000000005c4b7ee600000000ab91dcb6> {
           date: "2015-03-28 06:37:22",
           timezone_type: 3,
           timezone: "UTC"
       }
   ]

>>> $article->save();
=> true

#查看数据结果,添加了一条记录

>>> App\Article::all()->toArray();
=> [
       [
           "id"           => "1",
           "title"        => "My First Article",
           "body"         => "Some content...",
           "published_at" => "2015-03-28 06:37:22",
           "created_at"   => "2015-03-28 06:38:53",
           "updated_at"   => "2015-03-28 06:38:53"
       ]
   ]

>>> $article->title = 'My First Update Title';
=> "My First Update Title"

>>> $article->save();
=> true

>>> App\Article::all()->toArray();
=> [
       [
           "id"           => "1",
           "title"        => "My First Update Title",
           "body"         => "Some content...",
           "published_at" => "2015-03-28 06:37:22",
           "created_at"   => "2015-03-28 06:38:53",
           "updated_at"   => "2015-03-28 06:42:03"
       ]
   ]
   
>>> $article = App\Article::find(1);
=> <App\Article #000000005c4b7e1600000000ab91a676> {
       id: "1",
       title: "My First Update Title",
       body: "Some content...",
       published_at: "2015-03-28 06:37:22",
       created_at: "2015-03-28 06:38:53",
       updated_at: "2015-03-28 06:42:03"
   }

>>> $article = App\Article::where('body', 'Some content...')->get();
=> <Illuminate\Database\Eloquent\Collection #000000005c4b7e1800000000ab91a676> [
       <App\Article #000000005c4b7e1b00000000ab91a676> {
           id: "1",
           title: "My First Update Title",
           body: "Some content...",
           published_at: "2015-03-28 06:37:22",
           created_at: "2015-03-28 06:38:53",
           updated_at: "2015-03-28 06:42:03"
       }
   ]

>>> $article = App\Article::where('body', 'Some content...')->first();
=> <App\Article #000000005c4b7e1900000000ab91a676> {
       id: "1",
       title: "My First Update Title",
       body: "Some content...",
       published_at: "2015-03-28 06:37:22",
       created_at: "2015-03-28 06:38:53",
       updated_at: "2015-03-28 06:42:03"
   }
>>> 

>>> $article = App\Article::create(['title' => 'New Article', 'body' => 'New body', 'published_at' => Carbon\Carbon::now()]);
Illuminate\Database\Eloquent\MassAssignmentException with message 'title'</code>

MassAssignmentException, laravel은 레코드를 직접 삽입하지 못하도록 보호합니다. 예를 들어, 일부 특수한 경우 데이터베이스 레코드를 채우기 위해 양식 정보를 직접 사용해야 하지만 양식에 비밀번호 필드를 추가하지 않은 경우 해커가 비밀번호 필드를 생성하여 우리와 함께 서버로 다시 보냅니다. 다른 필드를 사용하면 수정이 발생합니다. 비밀번호는 위험하므로 모델의 어떤 필드를 직접 채울 수 있는지 laravel에 명시적으로 알려야 합니다.

모델 파일 수정 Article.php

<code><?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model {

	protected $fillable = [
        &#39;title&#39;,
        &#39;body&#39;,
        &#39;published_at&#39;
    ];

}</code>

은 제목, 본문, 출판_위치를 직접 입력할 수 있다는 의미입니다.

Tinker를 종료하고 다시 들어가세요

<code>
>>> $article = App\Article::create(['title' => 'New Article', 'body' => 'New body', 'published_at' => Carbon\Carbon::now()]);
=> <App\Article #000000005051b2c7000000007ec432dd> {
       title: "New Article",
       body: "New body",
       published_at: <Carbon\Carbon #000000005051b2c6000000007ec4081d> {
           date: "2015-03-28 06:55:19",
           timezone_type: 3,
           timezone: "UTC"
       },
       updated_at: "2015-03-28 06:55:19",
       created_at: "2015-03-28 06:55:19",
       id: 2
   }
   
# It's ok

>>> App\Article::all()->toArray();
=> [
       [
           "id"           => "1",
           "title"        => "My First Update Title",
           "body"         => "Some content...",
           "published_at" => "2015-03-28 06:37:22",
           "created_at"   => "2015-03-28 06:38:53",
           "updated_at"   => "2015-03-28 06:42:03"
       ],
       [
           "id"           => "2",
           "title"        => "New Article",
           "body"         => "New body",
           "published_at" => "2015-03-28 06:55:19",
           "created_at"   => "2015-03-28 06:55:19",
           "updated_at"   => "2015-03-28 06:55:19"
       ]
   ]

>>> $article = App\Article::find(2);
=> <App\Article #000000005051b22b000000007ec432dd> {
       id: "2",
       title: "New Article",
       body: "New body",
       published_at: "2015-03-28 06:55:19",
       created_at: "2015-03-28 06:55:19",
       updated_at: "2015-03-28 06:55:19"
   }

>>> $article->update(['body' => 'New Updaet Body']);
=> true

#update自动调用save()
</code>

이상에서는 Laravel 5(7) - Eloquent(laravel의 ORM)의 기본 사항을 다양한 측면을 포함하여 소개했습니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.