通过宏动态建立morphToMany关系

时间:2019-04-11 11:48:04

标签: php laravel laravel-5 eloquent eloquent--relationship

我想在模型(例如,用户,附件等)和基于文件包的文件模型之间动态添加morphToMany关系。 ServiceProvider应该建立关系。

我该怎么做?

PHP:

$fileables = config('topredmedia-filemanager.fileable');

foreach ((array)$fileables as $modelType) {
  if (class_exists($modelType)) {
    $model = App::makeWith($modelType);

    // Add Relation to all specified models in config
    Builder::macro('files', function () use ($model) {
      return $model->morphToMany(File::class, 'fileable', 'trm_fileables');
    });
  }
}

当我运行此代码但使用morphMany关系时,一切正常。

当我在控制器中执行$model->files()->sync([1, 2, 3])时,数据透视表(file_id,fileable_id,fileable_type)应填充正确的数据,但是当我运行它时,出现以下错误:

  

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fileable_id' cannot be null (SQL: insert into trm_fileables (file_id, fileable_id, fileable_type) values (3, , Path\To\Model\User))

0 个答案:

没有答案