如果优化简单逻辑调用谢谢

User 模型关系

   public function videoLikes():MorphToMany
    {
        return $this->morphedByMany(Video::class,'likeable')->withTimestamps();
    }
    public function comicLikes():MorphToMany
    {
        return $this->morphedByMany(Comic::class,'likeable')->withTimestamps();
    }

User 模型动作


    public function attachComicLike(int $id,int $type)
    {
        if ($type==1)
        {
            $this->comicLikes()->sync([$id], false);

        }elseif($type==2)
        {
            $this->videoLikes()->sync([$id], false);

        }
    }

在Comic 控制器调用

auth()->user()->attachComicLike(1,1);

在Video控制器调用

auth()->user()->attachComicLike(1,2);

请问下 User 模型中任何优化判断 让在使用的时候 只需要

    public function show(Comic $comic)
    {
    //这样无论comic 种调用 还是 video种调用只需要传入模
        auth()->user()->attachComicLike($comic);
        auth()->user()->attachComicLike($video); //Video 控制器中
    }

    请问下在User 模型中如何修改 谢谢
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

没测试过,你试一下。

public function attachComicLike(Model $model)
{
    if ($model instanceof Comic) {
        $relation = comicLikes;
    }else if($model instanceof Video){
        $relation = videoLikes;
    }

    $this->$relation()->sync([$model->id], false);
}
2年前 评论
李小明 (楼主) 2年前
讨论数量: 2

没测试过,你试一下。

public function attachComicLike(Model $model)
{
    if ($model instanceof Comic) {
        $relation = comicLikes;
    }else if($model instanceof Video){
        $relation = videoLikes;
    }

    $this->$relation()->sync([$model->id], false);
}
2年前 评论
李小明 (楼主) 2年前

if ($type=1)??

不是应该if ($type==1)吗?

2年前 评论
skys215 (作者) 2年前
李小明 (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!