我正在尝试使用db事务进行查询。当我的方法运行该时间时,数据已正确插入相应的表中,但它返回null。
我的代码
return $result = DB::transaction(function() use ($attributes) {
$service = $this->service->create($attributes);
$visibilityAttributes = $attributes['dropdown_option_id'];
$visibilityAttributes = array_map('intval', $visibilityAttributes);
$service->visibility()->sync($visibilityAttributes);
},3);
答案 0 :(得分:1)
如果要返回任何值,请尝试以下代码:
$result = DB::transaction(function() use ($attributes) {
$service = $this->service->create($attributes);
$visibilityAttributes = $attributes['dropdown_option_id'];
$visibilityAttributes = array_map('intval', $visibilityAttributes);
$service->visibility()->sync($visibilityAttributes);
return $service;
},3);
return $result
答案 1 :(得分:1)
DB::transaction()
返回传递给它的闭包返回的内容。由于关闭没有返回任何内容,因此DB::transaction()
将返回null
。您需要在闭包中添加return
语句。
return $result = DB::transaction(function() use ($attributes) {
$service = $this->service->create($attributes);
$visibilityAttributes = $attributes['dropdown_option_id'];
$visibilityAttributes = array_map('intval', $visibilityAttributes);
$service->visibility()->sync($visibilityAttributes);
// This value will be returned from DB::transaction().
return $service;
},3);
答案 2 :(得分:0)
通过返回值oustide函数尝试下面的代码。
$result = DB::transaction(function() use ($attributes) {
$service = $this->service->create($attributes);
$visibilityAttributes = $attributes['dropdown_option_id'];
$visibilityAttributes = array_map('intval', $visibilityAttributes);
$service->visibility()->sync($visibilityAttributes);
},3);
return $result;