调用关联的eloquent模型的类方法

时间:2016-07-07 12:48:09

标签: php laravel eloquent

我无法弄清楚如何调用类函数,在这种情况下File->saveFile()通过父类Article

class Article extends Model {
  public $table = 'pl_gen_article';

  public function background_image () {
    return $this->morphOne('App\Ubercms\File', 'fileable');
  }
}

class File extends Model {
  public $table = 'ubercms_file';

  public function saveFile (UploadedFile $file) {}
}


$articleId = \Route::input('id');
$article = Article::findOrFail($articleId);
$file = $request->file('image');

// ----------------------
// Attempts

// 1.
$article->background_image->saveFile($file)

// 2.
$image = new $article->background_image();
$image->saveFile($file);

如何从File模型创建Article模型实例?

1 个答案:

答案 0 :(得分:0)

通过Laravel Api文档跟踪$article->background_image()作为MorphOne实例的响应,我可以调用firstOrNew返回File实例,我能够之后致电saveFile

$model = $article->background_image()->firstOrNew([]);
$model->saveFile($file);