본문 바로가기

Modern PHP

Laravel - DB 쿼리 Facade & Eloquent ORM 발췌요약


직접 쿼리

$php artisan tinker

>>> DB::select('select * from posts');

라라벨은 PDO를 이용하기 때문에 아래 처럼 데이터 바인딩 처리가 필요

>>> DB::insert('insert into posts(title, body) values(?, ?)', ['Second Title', 'Second Body']);

Collection(=row)이 아닌 하나의 Instance(field)만 가져올 때

>>> $post = DB::selectOne('select * from posts where id = ?', [1]);
=> {#689
     +"id": 1,
     +"title": "라라벨",
     +"body": "라라벨 기억하기",
   }
>>> $post->title; // field 추출
=> "라라벨"
>>> DB::update('update posts set title="Modified Title" where id = ?', [2]); // 업데이트
=> 1




파사드 쿼리 빌더

$php artisan tinker

>>> DB::table('table_name')->get();
>>> DB::table('table_name')->find(2); // id select
>>> DB::table('table_name')->first(2); // first row select

>>> DB::table('table_name')->where('id', 1)->get();

>>> DB::table('table_name')->whereId(1)->get(); // Dynamic Method

where(function($query) {$query->where('field', 'operator', 'value);}) // where에 Closure 사용

>>> DB::table('table_name')->select('title')->get(); // field select


DB 쿼리 다양한 메소드들


count()

distinct()

select(DB::raw('count(*) as cnt'))

join()

union()

whereNull()

having()

groupBy()

등등..



레퍼런스


insert(array $value)

update(array $values)

delete(int $id)

lists(string $column)

orWhere(string $column, string $operator, mixed $value)

limit(int $value) // == take(int $value)

orderBy(string $column, string $direction)

latest() // == orderBy('created_at', 'desc')




엘로퀀트 ORM

라라벨에서 모델관련 php 파일 생성

$ php artisan make:model Post
$ php artisan make:model Author

app/ 폴더 하위에 생성


* 규칙 : 테이블 이름은 posts 와 같이 복수로, 모델 이름은 Post 처럼 단수

* 다른 경우, Post.php 모델에 protected $table = '테이블명'; 명시

 


$ php artisan tinker

>>> App\Author::get(); # == DB::table('authors')->get();

대부분의 쿼리 빌더 메소드는 엘로퀀트 모델에서도 사용 가능


Instance 생성 후 DB 저장

>>> $author = new App\Author;
>>> $author->email = 'foo@bar.com';
>>> $author->password = 'password';
>>> $author->save();  # 만든 인스턴스를 DB에 저장

QueryException

예외 발생시 timestamp값 입력을 아래처럼 비활성화 또는 문제의 필드(updated_at, created_at) 추가

class Author extends Model
{
    public $timestamps = false;
}

모델에 변경이 생기면 실행중이던 tinker 를 다시 실행


save() 대신 create() 메소드로 모델 생성

>>> App\Author::create([
...'email' => 'bar@bax.com',
...'password' => bcrypt('password') # 암호화된 60 Byte 스트링 생성 Facade로는 Hash::make(string $value)
... ]);

MassAssignmentException

create() 메소드로 모델 인스턴스 생성시 해당 모델 $fillable 속성을 지정 (악의적 입력을 방지)

class Author extends Model
{
    protected $fillable = ['email', 'password'];
}

tinker 재시작 후, create() 메소드 다시 시도

>>> App\Author::create([
... 'email' => 'bar@baz.com',
... 'password' => bcrypt('password')
... ]);
=> App\Author {#680 # bcrypt() Helper에 의해 암호화된 60 byte 패스워드를 확인하자.
     email: "bar@baz.com",
     password: "$2y$10$tL/9voTNRtH7dfE9yULVaOybUWTcNkLRws9gTawcU85L3PEwRotUS",
     id: 3,
   }






이 내용은 http://l5.appkr.kr 의 강좌 내용을 발췌, 제가 필요한 부분만 간략 정리한 버전입니다.

'Modern PHP' 카테고리의 다른 글

Laravel - DB 마이그레이션 (table 버전관리)  (0) 2018.05.12