php 如何在 Laravel 中保存多态关系?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42950104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save in a polymorphic relationship in Laravel?
提问by Dubby
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?
这些都不起作用。谁能给我一个我可以尝试的线索?
回答by Jo?o Mantovani
It's simple like that, see thissection.
就这么简单,请看本节。
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);
回答by Kurt Chun
you missed a step in the associate method, use this:
您错过了关联方法中的一个步骤,请使用:
$tag->videos()->associate($video)->save();
回答by Ali Sharifineyestani
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