[Laravel] Model

[Laravel] Model updated_at: 2024-06-27 12:23

Model

기본적인 모델형태

가장 기본 적인 형태

  • User.php
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
}

예 1

좀더 복잡한 Model을 가지고 상세 옵션을 설명해 보겠습니다.

<?php

namespace App\Models\Auth\User;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{

  // config > database의 connection에 설정한 정보로 없을 경우 default로 mysql이 들어간다.
  protected $connection = 'mysql'; // 생략가능

  // The database table used by the model.
  // 생략가능, 생략시에는 자동으로 User(클래스내임) -> users로 인식
  protected $table = 'users';

  // 생략가능, 자동 증가
  protected $incrementing = true;

  // The attributes that are mass assignable.
  // firstOrCreate 등을 사용할 경우 반드시 이 부분을 정의해 주어야 함
  protected $fillable = ['name', 'email'];


  // The attributes that should be hidden for arrays.
  // 숨김속성, 별도로 표기하지 않는한 Select의 결과로서 제외되는 항목
  protected $hidden = ['password', 'remember_token'];

  
  // The attributes that should be mutated to dates.
  // date가 별도 입력없이 null로 처리
  // created_at 이나 updated_at은 자동으로 입력됨
  protected $dates = ['deleted_at'];

  const CREATED_AT = null; // created_at 을 사용하지 않을경우(table에 없을 경우)
  const UPDATED_AT = null; // updated_at 을 사용하지 않을경우(table에 없을 경우)
  const CREATED_AT = '다른 필드명'; // 다른 필드명으로 CREATED_AT을 사용할 경우
}

$connection

생략될 시 config/database.php에서 정의된 mysql 을 가지고 다른 커넥션(멀티 데이타베이스)을 사용할 경우 아래와 같이 정의한다.
이렇게 정의해 두면 controller등에서 사용할 경우 별도의 정의없이 바로 사용가능하다.

protected $connection = 'mysql2';

$table

protected $table = '테이블 명';

$table은 아래의 경우 생략이 가능한데 이럴경우 laravel에서의 아래처럼 인식합니다.

  • 클래스명이 User 일경우 앞의 대문자가 소문자로 바뀌고 뒤에 s가 붙으면 실제 테이블 명이 됩니다. (User -> users, Logs -> logs)
  • 클래스명이 MarketOrder 일경우 첫번째 대문자는 소문자로 두번째 대문자 앞에는 '_' 가 붙고 소문자로 그리고 마지막은 s가 붙습니다. (MarketOrder -> market_orders)
  • DeliveryCompany -> delivery_companies (영어의 단복수 규칙을 따릅니다.)

SoftDeletes

deleted_at 이라는 부분이 필드에 추가 되어야 하며 $table->delete() 시 deleted_at에 삭제일이 들어가며, 실제 select시 deleted_at이 null 이 아닌 것은 가져오지 않습니다.


use Illuminate\Database\Eloquent\SoftDeletes;
..........

class User extends Model
{
  use  SoftDeletes; // SoftDeletes 는 별도정의 없이 필드에 deleted_at을 추가
  ..........
}

Sortable

리스트를 가져올때 정렬할 필드를 설정해 둡니다.

use Kyslik\ColumnSortable\Sortable;
..........
class User extends Model
{
  use  Sortable; 
  
  // Sortable 은 아래와 같이 sort 할 필드를 정의
  public $sortable = ['id', 'email', 'name', 'active', 'created_at']; 
  ..........
}

Attribute

attribute는 하나의 필드처럼 호출하여 사용할 수 있어 매우 유용하다.

..........
class User extends Model
{
  ..........
  
  public function getFullNameAttribute(){
    return $this->first_name . ' ' . $this->last_name;
  }

  // 위의 함수처럼 시작은 get 으로 하고 뒤는 Attribute를 사용하면 라라벨에서는 자동으로 magic 함수가 적용되어 full_name을 리턴합니다.
}

위 처럼 Attribute가 정의되면 아래처럼 두가지 방법으로 호출 가능합니다.

{{ $user->full_name }} // 추천
{{{ Auth::user()->full_name }}} // 추천
{{{ Auth::user()->getFullNameAttribute() }}}

Relations

다른 테이블에서 정보를 가져올때 유용하나 리스트 같은 곳에 사용할 경우는 처음 부터 조인하여 가져오는 것이 유용합니다.

..........
class User extends Model
{
  ..........
  
  public function points()
  {
    return $this->hasMany('App\Models\UserPoint');
  }

  public function point()
  {
    $point = $this->points()->select('point')->orderBy('id', 'desc')->first();
    return $point ? $point->point : 0;
  }
}
{{ $user->points }} // hasMany 로 정의되어 있으므로 현재 user가 보유한 point를 보여줍니다.
{{ $user->point }} // points() 의 결과를 다시 하는 것인데 이렇게도 처리한다는 예시로만 봐 주시기를..

hasOne (일대일 대응)도 있으므로 참조 바랍니다.

hasMany

return $this->hasMany('App\Comment', 'foreign_key');

return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

Authenticatable

회원테이블을 구성할때는 라라벨에서 제공하는 기본 User를 extends 하여 사용 할 수도 있습니다.

..........
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
..........
}

JWTAuth

JSON Web Tokens에 관한 내용인데 이 부분은 JWT 구현에서 다시 설명 드리겠습니다.

..........
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
  ..........
  /**
   * Get the identifier that will be stored in the subject claim of the JWT.
   *
   * @return mixed
   */
  public function getJWTIdentifier()
  {
    return $this->getKey();
  }

  /**
   * Return a key value array, containing any custom claims to be added to the JWT.
   *
   * @return array
   */
  public function getJWTCustomClaims()
  {
    return [];
  }
  ..........
}

평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글