doubi7496 2017-01-17 17:39 采纳率: 0%
浏览 82
已采纳

在Laravel 5.3中同时保存多态关系

I want to correctly save both polymorphic relationships at the same time. The code below works, but I feel it could be a lot cleaner as I presume the two update() methods are calling the database twice.

A NewsModule::class can have different module items; VideoModule, TextModule, ImageModule, and a few more. Each containing their own content to be attached to the parent NewsModule.

As mentioned, the code works so the relationships are set up correctly, but I'm convinced there's a cleaner way of saving both at the same time.

I'm also open to suggestions about cleaning up the if statements too. But maybe that's another post.

public function update(Request $request, $id)
{
    $module = NewsModule::find($id);

    if ($module->type === 'text') {
        $content = TextModule::find($module->content_id);
    } elseif ($module->type === 'image') {
        $content = ImageModule::find($module->content_id);
    };

    $module->update($request->all());
    $content->update($request->all());

    return fractal()
        ->item($module, new NewsModuleTransformer)
        ->parseIncludes(['content'])
        ->toArray();
}

Updated (more code by request)...

Structure:

news_modules
    - id
    - content_id
    - content_type
    - etc

text_modules
    - id
    - content
    - etc

image_modules
    - id
    - image_id
    - etc

NewsModule:

class NewsModule extends Model
{
    public function content()
    {
        return $this->morphTo();
    }
}

All item modules:

class TextModule extends Model
{
    public function newsmodules()
    {
        return $this->morphMany(NewsModule::class, 'content');
    }
}
  • 写回答

1条回答 默认 最新

  • dougu3988 2017-01-17 18:35
    关注
    public function update(Request $request, $id)
    {
        $modele = NewsModule::find($id);
    
        $module->update($request->all());
    
        $module->content->update($request->all());
    
        return fractal()
            ->item($module, new NewsModuleTransformer)
            ->parseIncludes(['content'])
            ->toArray();
    }
    

    That will run 4 queries total. 1 for each module to retrieve and another to update. That can be cut down to 3 like:

    public function update(Request $request, $id)
    {
        $modele = NewsModule::find($id);
    
        $module->update($request->all());
    
        $module->content()->update($request->all());
    
        return fractal()
            ->item($module, new NewsModuleTransformer)
            ->parseIncludes(['content'])
            ->toArray();
    }
    

    The downside to $module->content()->update($request->all()); is it will throw an error if there is anything in $request->all() that isn't a column in that content model or there is an array as a value. You can avoid that by just calling update() on the $fillable properties (if you have them defined) of the related model like:

        $fillable = $module->content()->getRelated()->getFillable();
        $module->content()->update($request->only($fillable));
    

    This way will also not fire any model event listeners you have since you are never retrieving the model from the database.

    To take everything one step further, look into Route Model Binding. In your app\Providers\RouteServiceProvider's boot() method:

    public function boot()
    {
        parent::boot();
    
        Route::model('news', App\NewsModule::class);
    }
    

    This way 'news' will always resolve to an instance of NewsModule when using it as a route parameter. So your route would be something like:

    Route::match(['patch', 'put'], '/news/{news}', 'NewsController@update');
    

    So in your update method you could resolve the model by just type hinting it in the method allowing you to do:

    public function update(Request $request, NewsModule $news)
    {
        $news->update($request->all());
    
        $news->content->update($request->all());
    
        return fractal()
            ->item($news, new NewsModuleTransformer)
            ->parseIncludes(['content'])
            ->toArray();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载