duanniwu7730 2016-07-07 12:48
浏览 31
已采纳

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

I'm having trouble figuring out how to call a class function, in this case File->saveFile() through the parent class 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);

How do I create a File model instance from Article model?

  • 写回答

1条回答 默认 最新

  • dqef7931 2016-07-07 13:11
    关注

    Through the Laravel Api Docs traced the response of $article->background_image() which as MorphOne instance, where I can call firstOrNew which returns an File instance and I'm able to call saveFile afterwards.

    $model = $article->background_image()->firstOrNew([]);
    $model->saveFile($file);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?