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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题