我正在阅读有关如何在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);
这些都不起作用。谁能给我一些关于我可以尝试的线索?
答案 0 :(得分:12)
这很简单,请参阅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);
答案 1 :(得分:1)
你也可以试试这个对我有用的(morphMany):
$rel_data = ['assigned_type'=>'User','assigned_id'=>$user_model->getKey()];
$event->assigned_models()->create($rel_data);
答案 2 :(得分:0)
如果要保存多个标签,可以使用下面的代码
路线:
Route::post('posts/{id}/tags', 'PostController@storeTags');
您的请求将标签发送为包含ID的数组
+ 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
答案 3 :(得分:0)
我使用此代码:
$post->comments->attach($comment);