lundi 14 novembre 2016

Laravel 5 insert mutiple rows into pivot table

I wrote a function see:

public function store(Request $request)
{
    $input = $request->all();

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

try {       

        $item = new Items();
        $cat = Category::find($request->cid);
        $tags = "";
        $tags_desc = "";
        for ($i=1;$i<=count($request->tags);$i++) {
            $tags .= $request->tags[$i].'---';
            $tags_desc .= $request->tags_desc[$i].'---';
        }

        $tag_ids = array();

        for ($i=1;$i<=count($request->tags);$i++) {
            $tag_ids[$request->tags[$i]] = array('description' => $request->tags_desc[$i]);
        }           

        $desc = $tags.$tags_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()) {
            //$tag_ids = array(1);
            $item->tags()->sync($tag_ids);
            $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');
    }

    return response($request);
}

the main problem about this function is

$tag_ids = array();

for ($i=1;$i<=count($request->tags);$i++) {
    $tag_ids[$request->tags[$i]] = array('description' => $request->tags_desc[$i]);
}

if the tags[$i] is duplicated for example

$tag_ids[2] = array ('description' => 'row 1');
$tag_ids[2] = array ('description' => 'row 2');

the next one will overwrite the first one, so finally the function will only insert 1 row into db. how to fix this problem?

Please don't mark "is duplicated question" Laravel attach pivot to table with multiple values

the problems is different from above post.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire