20210419のlaravelに関する記事は1件です。

laravel クエリビルダで使用するsave()メソッドってどこに記載されているんだろう?

目的 クエリビルダを使ってDBに値を格納する時のsave()メソッドはどこで定義されているのか気になったので調べてみた 結果 アプリ名ディレクトリ/todos/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.phpの中で定義されていた。 情報 筆者がプライベートで使用しているlaravelの簡単なメモアプリのファイルを用いて下記の内容を確認した。 詳細 Memoモデルファイルを見てみる。 任意のモデルファイルを確認したところ下記のように記載されていた。 アプリ名ディレクトリ/todos/app/Models/Memo.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Memo extends Model { use HasFactory; } extends Modelと記載されているのでModelクラスを継承して上記のMemoクラスが作成されていることがわかる。 use Illuminate\Database\Eloquent\Model;のように継承元が記載されているので当該のクラスを確認してみる。 継承元のファイルを見てみる。 use宣言からファイルパスを確認し、継承元のクラスが記載されているファイルを発見した。 アプリ名ディレクトリ/todos/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.phpに継承元のクラスが記載されていた。内部のメソッドを一部抜粋して記載する。 アプリ名ディレクトリ/todos/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php /** * Save the model to the database. * * @param array $options * @return bool */ public function save(array $options = []) { $this->mergeAttributesFromClassCasts(); $query = $this->newModelQuery(); // If the "saving" event returns false we'll bail out of the save and return // false, indicating that the save failed. This provides a chance for any // listeners to cancel save operations if validations fail or whatever. if ($this->fireModelEvent('saving') === false) { return false; } // If the model already exists in the database we can just update our record // that is already in this database using the current IDs in this "where" // clause to only update this model. Otherwise, we'll just insert them. if ($this->exists) { $saved = $this->isDirty() ? $this->performUpdate($query) : true; } // If the model is brand new, we'll insert it into our database and set the // ID attribute on the model to the value of the newly inserted row's ID // which is typically an auto-increment value managed by the database. else { $saved = $this->performInsert($query); if (! $this->getConnectionName() && $connection = $query->getConnection()) { $this->setConnection($connection->getName()); } } // If the model is successfully saved, we need to do a few more things once // that is done. We will call the "saved" method here to run any actions // we need to happen after a model gets successfully saved right here. if ($saved) { $this->finishSave($options); } return $saved; } save()メソッドを発見した。その他にもクエリビルダで使用するメソッドが多数記載されていた。各モデルクラスがModelクラスを継承してつくられていたからsave()メソッドが使用できたのか。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む