0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel 5.6 コードスニペット集(Modelリレーション編)

Last updated at Posted at 2022-09-28

親子関係(1対多)にあるテーブルのModelのコード例です。

外部キー制約を使用しないケースで、主テーブルのデータ削除時、従テーブルのID紐づきデータも一括操作したい場合
Model.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Person;

class Person extends Model
{

    /**
     * Bootstrap any application services.
     * 
     * @return void
     */
    public static function boot()
    {
        parent::boot();
        // 親データ削除時:子テーブルのid紐付レコードも削除
        static::deleting(function ($person) {
            $person->schedule()->delete();
            $person->company()->delete();
            $person->position()->delete();
            $person->assessment()->delete();
        });
        // 親データ削除時:従テーブルの親ID欄はnull挿入
        static::deleting(function ($person) {
            $person->schedules()->update(['person_id' => null]);
        });
        // 状態フラグを無効設定時:従テーブルのデータはnull挿入
        static::updating(function ($person) {
            if($person->status_flg === '1') {
                $person->schedules()->update(['person_id' => null]);
            }
        });
    }
日付けデータ等、DATE型で保存した値を取得時、常に加工しておきたい場合
Model.php
    /**
     * Get schedule date as 'Y-m-d' format.
     * @param mixed $value
     */
    public function getScheduleDateAttribute() // get...Attribute()の...に取得・加工するカラム名をアッパーキャメル形式で記載
    {
        return date_format(date_create($this->schedule_date), 'Y-m-d');
    }
    /**
     * Get schedule time as 'H:i' format.
     * @param mixed $value
     */
    public function getScheduleTimeAttribute()
    {
        return date_format(date_create($this->schedule_time), 'H:i');
    }

Modelへのリレーション設定
Model.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Company;
use App\Models\Person;

class Schedule extends Model
{

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function Person() // 記載はModel同様アッパーキャメル形式。belongTo側は単数形、hasMany側は複数形。
    {
        return $this->belongsTo(Person::class, 'person_id', 'id'); // 第2引数以降は、不要。但し、指定する外部キーが●●_id形式以外だったり、特定の外部キーを指定したい場合は必要。
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BlongsTo
     */
    public function schedules()
    {
        return $this->hasMany(Schedule::class, 'company_id', 'id');
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?