mardi 15 novembre 2016

laravel 5 how to update (and also add new) multiple rows in Pivot table

I have an udpate function in backend, an item has many tags, in Item model:

public function tags()
{
    return $this->belongsToMany('App\Tags','items_tags','items_id','tags_id')->withPivot('id','description')->withTimestamps();
}

the update function:

public function update(Request $request,$id)
{

    $input = $request->all();

    $success = false;
    DB::beginTransaction();

try {       

        $item = new Items();
        $item = Items::find($id);
        $cat = Category::find($request->cid);
        $tags_array = $request->tags;

        //$tags_desc = "";
        $tag_ids = array();

        //$text = "";

        foreach ($tags_array as $value) {
            $tag_ids[][$value['g1tags']] =  array('description' => $value['g1tags_desc'], 'gid' => 1);
        }

        //$desc = $tags.$tags_desc.$request->description;
        $desc = $request->description;
        $item->title = $request->title;
        $item->description = $desc;
        $item->item_alias = $request->item_alias;
        //$item->cid = $request->cid;
        $item->item_flavor = $request->item_flavor;
        $item->item_channel = $request->item_channel;
        $item->item_function = $request->item_function;
        $item->item_cure = $request->item_cure;  
        $item->item_buy = $request->item_buy;

        $item->category()->associate($cat);

        if ($item->save()) {

            foreach($tag_ids as $tag_id) {
                $item->tags()->sync($tag_id);
            }
            $success = true;
        }

    } catch (\Exception $e) {
        // maybe log this exception, but basically it's just here so we can rollback if we get a surprise
    }

    if ($success) {
        DB::commit();
        //return Redirect::back()->withSuccessMessage('Item saved');
    } else {
        DB::rollback();
        //return Redirect::back()->withErrorMessage('Something went wrong');
    }
    //die();        
    return response($item);
}

the DB pivot table has the following columns:

id, created_at,updated_at,description,gid,enabled,tags_id,items_id

The sync function seems only can update the rows by tags_id but not id, anyone know how to update (and also add new) the rows in pivot table? Detach everything is only way to do that?

i've tried to use but not work

            foreach ($tags_array as $value) {

                $tag_ids[] =  array(
                'id'  => $value['g1tags_id'], 
                'tag_id'  => $value['g1tags'],              
                'description' => $value['g1tags_desc'], 
                'gid' => 1);
            }

$item->tags()->newPivotStatement()->where('id', $tag_id['id'])->update($tag_id['g1tags_desc']);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire