【问题标题】:How to save in a polymorphic relationship in Laravel?如何在 Laravel 中保存多态关系?
【发布时间】:2017-08-14 11:25:38
【问题描述】:

我正在阅读有关如何在 Laravel 中定义多对多多态关系的教程*,但它没有说明如何使用这种关系保存记录。

在他们的例子中

class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}

class Tag extends Model
{
    /**
     * Get all of the posts that are assigned this tag.
     */
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'taggable');
    }

    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }
}

我尝试过以不同的方式保存,但对我来说最有意义的尝试是:

$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->associate($video);

or

$tag->videos()->sync($video);

这些都不起作用。谁能告诉我我可以尝试什么?

【问题讨论】:

  • 错误是什么?

标签: php laravel orm polymorphism


【解决方案1】:

就这么简单,见this部分。

您可以直接从关系的保存方法中插入评论,而不是手动设置视频的属性:

//Create a new Tag instance (fill the array with your own database fields)
$tag = new Tag(['name' => 'Foo bar.']);

//Find the video to insert into a tag
$video = Video::find(1);

//In the tag relationship, save a new video
$tag->videos()->save($video);

【讨论】:

  • 如果不起作用,请编辑您的帖子并为我们解释您的关系
  • 谢谢。那解决了它。我是如此接近。
  • @João Mantovani 看来你可以帮助我。看看这个:stackoverflow.com/questions/49512956/…
  • @JoãoMantovani 如果 tag() 是带有 taggable() morphTo() 的多态模型,你怎么可能在 tag() 模型上有视频() 关系?
  • 而不是$tag->videos()->save($videos) 使用$video->tags()->save($tag),因为视频模型有很多标签并在您的video 模型中设置morphTo
【解决方案2】:

你错过了 associate 方法中的一个步骤,使用这个:

$tag->videos()->associate($video)->save();

【讨论】:

    【解决方案3】:

    你也可以试试这个对我有用的(morphMany):

    $rel_data = ['assigned_type'=>'User','assigned_id'=>$user_model->getKey()];
    
    $event->assigned_models()->create($rel_data);
    

    【讨论】:

      【解决方案4】:

      如果你想保存多个标签,你可以使用下面的代码

      路线:

      Route::post('posts/{id}/tags', 'PostController@storeTags');
      

      您的请求发送标签作为数组包含 ids

      + Request (application/json) or (form-data)
              {
                  "tags": [
                    1,2,3,4
                  ]
              }
      

      在您的控制器中:

      public function storeTags(Request $request, $id)
      {
          foreach ($request->tags as $id)
              $tags[] = Tag::find($id);
      
          $post= Post::find($id);
          $post->tags()->saveMany($tags);
      
      }
      

      以及更新:

      // sync() works with existing models' ids. [here means: $request->tags]
      $post->tags()->sync([1,2,3]); // detaches all previous relations
      $post->tags()->sync([1,2,3], false); // does not detach previous relations,attaches new ones skipping existing ids
      

      【讨论】:

        【解决方案5】:

        我使用这个代码:

        $post->comments->attach($comment);
        

        【讨论】:

          【解决方案6】:

          comment.php

          class Comment extends Model
          {
          use HasFactory;
          protected $fillable = ['body','comment_id','comment_type'];
          public function commentable()
          {
              return $this->morphTo();
          }
          }
          

          MainController.php

           public function addPost(){
              //add Post
              //Create a new Tag instance (fill the array with your own database fields)
              $post = new Post(['post_name' => 'something post ']);
              
              //Find the comment to insert into a post
              $comment =  Comment::find(1);
          
              //In the comment relationship, save a new post
              $post->save();
              return ("Post Added");
              }
          

          web.php

          Route::get('/add-post',[MainController::class,'addPost']);
          

          https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-02-15
            • 1970-01-01
            • 2014-07-16
            • 1970-01-01
            • 2015-03-05
            • 1970-01-01
            • 2020-10-13
            • 2022-10-25
            相关资源
            最近更新 更多