如何在Laravel中保存多个到多个多态关系的条目? [英] How to save entries in many to many polymorphic relationship in Laravel?

查看:185
本文介绍了如何在Laravel中保存多个到多个多态关系的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组织模型和一个标签模型。我想将标签与组织相关联。我的数据库表和Eloquent模型设置如下...

  org 
id - integer
name - string
...

标签
id - 整数
名称 - 字符串

taggables
id - 整数
taggable_id - integer
taggable_type - string

// app / models / Org.php
class Org extends Eloquent
{
protected $ table =org;

...

public function tags()
{
return $ this-> morphToMany('Tag','taggable');
}
}

// app / models / Tag.php
class标签扩展Eloquent
{
protected $ table =tags ;
public $ timestamps = false;

public function org()
{
return $ this-> morphedByMany('Org','taggable');
}
}

在我看来,我有一个多重的表单选择框,用户可以选择他/她想要与组织关联的标签...

  ... 
{{Form :: select('tags []',$ tag_options,null,array(
'multiple',
'data-placeholder'=>'选择一些标签'))
}}
...

...而$ tag_options来自我的routes.php文件...

 查看:: composer('*',function($ view)
($($ tags)> 0)
{
$ tag_options = array_combine($ tags - > lists('id'),
$ tags-> lists('name'));
}
else
{
$ tag_options = array (null,'Unspecified');
}

$ view-> with('tag_options',$ tag_options);
});

当我的视图中的表单提交时,以下路由将捕获它来更新组织模型。

  Route :: put('org / {org}',function(Org $ org){
$ org-> description = Input :: get('description');
$ org-> website = Input :: get('website');
$ org-> tags =输入:: get('tags');
$ org-> save();

return Redirect :: to('org /'.$ org-> id)
- > with('message','Seccessfully updated page!');
});

现在,Input :: get('tags')只是一个数组的标签ID,表单

  [1,6,8] 

如何使用此标签将标签与组织相关联?



我也有评论设置为使用多态关系的组织,我只是这样做...

  Route :: put('org / post / {org}',function(Org $ org){
$ comment = new Comment;
$ comment-> user_id = Auth :: user() - > id;
$ comment - > body = Input :: get('body');
$ comment-> commentable_id = $ org-> id;
$ comment-> commentable_type ='Org';
$ comment-> save();

return Redirect :: to('org /'.$ org-> id)
- > with('message' 分开发表评论!);
});

然而,当我想关联一个多对多关系时,它并不简单或更多的标签与组织。



任何帮助都赞赏,谢谢!!

解决方案

可以使用所有 belongsToMany 方法,对于多态多对多扩展的关系:

  //我会将复数'entities()'中的标签称为更为准确的

$ tag-> entities() - > save(新的或现有的模型,数组的数据,触摸父= true)(在现有模型上使用)
$ tag-> entities() - > saveMany(新的或现有模型的数组,数组数组和数据的数据)
$ tag-> entities() - > attach(现有的model / id,数据透视数据,touch parent = true)
$ tag->实体) - > sync(ids的数组,detach = true)
$ tag-> entities() - > updateExistingPivot(pivot id,pivot数据,触摸数组)

所有这些方法都有两种方式。






示例:

  $ tag = Tag :: first(); 
$ entity = Entity :: find(10);

// save()适用于新创建和现有的两个模型:
$ tag-> entities() - > save(new Entity(...));
$ tag-> entities() - > save($ entity);

// saveMany()like above with new and / or existing models:
$ tag-> entities() - > saveMany([$ entity,new Entity 。)]);

// attach()适用于现有模型或其ID:
$ tag-> entities() - > attach($ entity);
$ tag-> entities() - > attach($ entity-> id);

// sync()适用于现有模型的ids:
$ tag-> entities() - > sync([1,5,10]); //分离所有以前的关系
$ tag-> entities() - > sync([1,5,10],false); //不分离以前的关系,附加新的跳过现有的ids






您的案例:

  Route :: put('org / {org}',function(Org $ org) {

$ org-> description = Input :: get('description');
$ org-> website = Input :: get('website');
$ org-> save();

$ org-> tags() - > sync(Input :: get('tags'));

//或者如果你不想分离以前的标签:
// $ org-> tags() - > sync(Input :: get('tags'),false);


返回Redirect :: to('org /'.$ org-> id)
- > with('message','Seccessfully updated page!');
});


I have an Org model and a Tag model. I want to associate tags with organizations. My database tables and Eloquent models are set up like so ...

org
    id - integer
    name - string
    ...

tags
    id - integer
    name - string

taggables
    id - integer
    taggable_id - integer
    taggable_type - string

// app/models/Org.php
class Org extends Eloquent
{
    protected $table = "org";

    ...

    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }
}

// app/models/Tag.php
class Tag extends Eloquent
{
    protected $table = "tags";
    public $timestamps = false;

    public function org() 
    {
        return $this->morphedByMany('Org', 'taggable');
    }
}

In my view, I have a form with a multiple select box where the user can select the tags he/she wants to be associated with the organization ...

...
{{ Form::select('tags[]', $tag_options, null, array(
        'multiple',
        'data-placeholder' => 'Select some tags'))
}}
...

... And $tag_options comes from my routes.php file ...

View::composer('*', function($view)
{
    $tags = Tag::all();

    if(count($tags) > 0)
    {
        $tag_options = array_combine($tags->lists('id'),
                                    $tags->lists('name'));
    }
    else
    {
        $tag_options = array(null, 'Unspecified');
    }

    $view->with('tag_options', $tag_options);
});

When the form in my view is submitted, the following route will catch it to update the org model ...

Route::put('org/{org}', function(Org $org){
    $org->description = Input::get('description');
    $org->website = Input::get('website');
    $org->tags = Input::get('tags');
    $org->save();

    return Redirect::to('org/'.$org->id)
        ->with('message', 'Seccessfully updated page!');
});

Now, Input::get('tags') is just an array of the tag IDs, of the form

["1","6","8"]

How can I use this to associate the tags with the organization?

I also have comments set up for organizations using a polymorphic relationship where I just do this ...

Route::put('org/post/{org}', function(Org $org){
    $comment = new Comment;
    $comment->user_id = Auth::user()->id;
    $comment->body = Input::get('body');
    $comment->commentable_id = $org->id;
    $comment->commentable_type = 'Org';
    $comment->save();

    return Redirect::to('org/'.$org->id)
        ->with('message', 'Seccessfully posted comment!');
});

However, it's not as simple with a many-to-many polymorphic relationship when I want to associate one or more tags with an organization.

Any help is appreciated, thanks!!

解决方案

You can use all of the belongsToMany methods for this, for polymorphic many-to-many extends that relation:

// I would call that relation on tag in plural 'entities()' to be more accurate

$tag->entities()->save(new or existing model, array of pivot data, touch parent = true) (used on existing model)
$tag->entities()->saveMany(array of new or existing models, array of arrays with pivot data)
$tag->entities()->attach(existing model / id, array of pivot data, touch parent = true)
$tag->entities()->sync(array of ids, detach = true)
$tag->entities()->updateExistingPivot(pivot id, array of pivot data, touch)

All of those methods work both ways of course.


Examples:

$tag = Tag::first();
$entity = Entity::find(10);

// save() works with both newly created and existing models:
$tag->entities()->save(new Entity(...));
$tag->entities()->save($entity);

// saveMany() like above works with new and/or existing models:
$tag->entities()->saveMany([$entity, new Entity(...)]);

// attach() works with existing model or its id:
$tag->entities()->attach($entity);
$tag->entities()->attach($entity->id);

// sync() works with existing models' ids:
$tag->entities()->sync([1,5,10]); // detaches all previous relations
$tag->entities()->sync([1,5,10], false); // does not detach previous relations, attaches new ones skipping existing ids


Your case:

Route::put('org/{org}', function(Org $org){

  $org->description = Input::get('description');
  $org->website = Input::get('website');
  $org->save();

  $org->tags()->sync(Input::get('tags'));

  // or if you don't want to detach previous tags:
  // $org->tags()->sync(Input::get('tags'), false);


  return Redirect::to('org/'.$org->id)
    ->with('message', 'Seccessfully updated page!');
});

这篇关于如何在Laravel中保存多个到多个多态关系的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆