简体   繁体   English

Laravel中的多态关系如何保存?

[英]How to save in a polymorphic relationship in Laravel?

I'm reading the tutorial* on how to define many-to-many polymorphic relationships in Laravel but it doesn't show how to save records with this relationship.我正在阅读关于如何在 Laravel 中定义多对多多态关系的教程*,但它没有显示如何使用这种关系保存记录。

In the their example they have在他们的例子中,他们有

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

and

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');
    }
}

I've tried saving in different ways but the attempts that makes most sense to me is:我尝试过以不同的方式保存,但对我来说最有意义的尝试是:

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

or

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

None of these are working.这些都不起作用。 Can anyone give me a clue on what I could try?谁能告诉我我可以尝试什么?

It's simple like that, see this section.就这么简单,请看节。

Instead of manually setting the attribute on the videos, you may insert the Comment directly from the relationship's save method:您可以直接从关系的保存方法中插入评论,而不是手动设置视频的属性:

//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);

您错过了关联方法中的一个步骤,请使用:

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

You can also try this which worked for me (morphMany):你也可以试试这个对我有用的(morphMany):

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

$event->assigned_models()->create($rel_data);

And if you want to save multi tags you can use code below如果你想保存多个标签,你可以使用下面的代码

route:路线:

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

your request sends tags as array contains ids您的请求发送标签作为数组包含 ids

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

in your controller:在您的控制器中:

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

    $post= Post::find($id);
    $post->tags()->saveMany($tags);

}

and for update:和更新:

// 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

我使用这个代码:

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

Comment.php评论.php

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

MainController.php主控制器.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 web.php

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

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

$post = Post::create([
  'title' => 'test title',
  'description' => 'test description',
  'status' => 1,
  ]);

$post->comment()->create([ 'body' => "test body",'user_id' => 1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM