LoginSignup
2
5

More than 5 years have passed since last update.

Laravelでモデルの関連テーブルを動的に指定

Last updated at Posted at 2017-10-09

やりたかったこと

  • Modelクラスの関連テーブルを動的に指定する

 → Temporaryテーブル用にModelクラスを用意するのが面倒なので、Modelクラスを使いまわしたい

問題点

  • Modelクラスの関連テーブルをsetTable()メソッドを使用して設定できるが、save()メソッドなどを利用した場合に変更前の関連テーブルに対して実行されてしまう

原因

  • newInstance()メソッドでModelクラスの別インスタンスを生成し利用しているため、設定が反映されない

対応

  1. newInstance()メソッドをOverrideし、生成されたインスタンスのtableプロパティを設定する
Model.php
/**                                                                                            
 * Create a new instance of the given model.
 *
 * @param  array  $attributes
 * @param  bool  $exists
 * @return static
 */
public function newInstance($attributes = [], $exists = false)
{
    $model = parent::newInstance($attributes, $exists);

    // 設定されている関連テーブルを新しいインスタンスにも設定
    $model->setTable( $this->getTable() );
    return $model;
}

その他

  1. query()メソッドは(new static)のインスタンスに対するnewQuery()メソッドの結果を返すため、今回の対応では意味なし
  2. newQuery()メソッドでQueryBuilderを取得する必要がある
2
5
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
2
5