So speichern Sie die Einträge in viele, viele polymorphe Beziehung in Laravel?

Ich habe eine Org-Modell und ein-Tag-Modell. Ich will associate-tags mit Organisationen. Meine Datenbank-Tabellen und Eloquent Modelle sind so eingerichtet, 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 meiner Sicht, ich habe ein Formular mit mehreren select-box, wo der Benutzer kann wählen Sie die tags aus, die er/Sie sein will, im Zusammenhang mit der Organisation ...

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

... Und $tag_options, kommt aus meiner routes.php Datei ...

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

Wenn das Formular in meine anzeigen eingereicht werden, folgende route fangen wird es ein update der org-Modell ...

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

Nun, Input::get('tags') ist nur ein array mit den tag-IDs der form

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

Wie kann ich dieses zuordnen der tags mit der Organisation?

Ich habe auch Kommentare setzen sich für Organisationen, die eine polymorphe Beziehung, wo ich genau dies tun ...

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

Jedoch, es ist nicht so einfach mit einer viele-zu-viele polymorphe Beziehung, wenn ich zuordnen möchten, einen oder mehrere tags, die mit einer Organisation.

Jede Hilfe ist willkommen, danke!!

InformationsquelleAutor chipit24 | 2014-05-27

Schreibe einen Kommentar