catthr
4/15/2015 - 12:40 PM

Eloquent info Schema Builder Query Scope Relation

Eloquent info Schema Builder Query Scope Relation

Schema Builder

Проверка на то, что БД уже есть

if (Schema::hasTable('users'))
{
    //
}

Relations

Many to Many

$this->belongsToMany('model', 'table_name', 'model_id', 'this_id')

$article->tags()->attach(array) просто добавит новые связи

$article->tags()->dettach(array) удалит связи

$articles->tags()->sync(array) оставит только те связи, что есть в переданном массиве

Morphing Relations

Если в одном классе несколько полей ссылаются на другой объект, то можно добавить столбец в БД и по нему отбирать соответствующие поля:

public function mugshot() { 
    return $this->morphOne('Image', 'of')->where('type', 'mugshot'); 
}

public function photos() { 
    return $this->morphMany('Image', 'of')->where('type', 'photo'); 
}

Нужно не забывать сохранять правильно Взято отсюда

Scopes

У модели

public function scopePublished($query){
  $query->where('published_at', '<=', Carbon::now());
}

Использовать: Article::latest()->published()->get();

Модификаторы данных (Mutators)

public function setFieldNameAttribute ($data) {
  $this->attributes['name' = Carbon::parse($date);
}

Атрибуты

Можно добавить свойство, которого нет в БД, но использовать его как остальные

public function getIsAdminAttribute()
{
    return $this->attributes['admin'] == 'yes';
}

Чтобы свойство появилось при сериализации в JSON или array используется $appends

protected $appends = array('is_admin');

Общий сеттер для всех атрибутов setAttribute

public function setAttribute($key, $value)
{
    if(empty($value) && in_array ($key, $this->nullable)) {
        $value = null;
    }
    parent::setAttribute($key,$value);
}

Работа с датами

Чтобы Laravel преобразовывал поля дат к объектам Carbon:

protected $dates = ['published_at'];

Красивый вывод даты

$created_at->difforHumans() // => 3 days from now

Timestapms

По умолчанию, считает, что у модели есть created_at и updated_at свойства Чтобы оключить:

public $timestamps = false;

В schema builder

$table->timestamps();
$table->nullableTimestamps();
$table->dropTimestamps();

Чтобы только обновить timestaps поля

$model->touch();

Псевдо удаление

По умолчанию, отсутствует

v5 use Illuminate\Database\Eloquent\SoftDeletes;
v4 use \Illuminate\Database\Eloquent\SoftDeletingTrait;

Схема

$table->softDeletes();
$table->dropSoftDeletes();

Валидация

static $rules = [
        'email' => 'required|email|unique:users',
        'password' => 'required|confirmed',
        'role_id' => 'required|exists:roles,id'
    ];