简体   繁体   中英

Laravel - Check query execution after attach() and detach()

After I execute this

$shop->articles()->attach($article_id);

or this

$shop->articles()->detach($article_id);

how do I make sure they actually get executed? In the first case it returns void, but also it saves automatically so I cannot use the save function to check it. In the second case it returns int, but what does it represent?

You do it with try/catch and DB::transaction/commit/rollback .

try{
    \DB::transaction(function() use($shop, $article_id) {
        $shop->articles()->attach($article_id);
    });

    \DB::commit();
} catch (\Exception $e) {
    \DB::rollback();

    return redirect()->back()->withErrors(collect($e->getMessage()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM