无法在Laravel 5.1中获取刚刚保存在数据库中的数据

时间:2016-03-19 13:22:07

标签: laravel-5.1

我成功地将数据保存在数据库中。但是,保存后无法找到数据。

在JSON中,关键对象的值是一个空数组。

我的数据库架构:

CREATE TABLE IF NOT EXISTS `bigdata_db`.`objects` (
  `object_id` CHAR(34) NOT NULL,
  `object_lt_x` FLOAT NOT NULL,
  `object_lt_y` FLOAT NOT NULL,
  `object_width` FLOAT NOT NULL,
  `object_height` FLOAT NOT NULL,
  `image_id` CHAR(34) NOT NULL,
  `type_id` CHAR(34) NOT NULL,
  PRIMARY KEY (`object_id`),
  INDEX `fk_objects_images1_idx` (`image_id` ASC),
  INDEX `fk_objects_types1_idx` (`type_id` ASC),
  CONSTRAINT `fk_objects_images1`
    FOREIGN KEY (`image_id`)
    REFERENCES `bigdata_db`.`images` (`image_id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_objects_types1`
    FOREIGN KEY (`type_id`)
    REFERENCES `bigdata_db`.`types` (`type_id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

我的对象模型:

protected $table = 'objects';
public $timestamps = false;
protected $primaryKey = 'object_id';
public $incrementing = false;
protected $fillable = ['object_id','object_lt_x', 'object_lt_y', 'object_width', 'object_height', 'image_id', 'type_id'];

将数据保存到数据库

$obj = new Object;
$obj->object_id = $objectId;
$obj->object_lt_x = $objX;
$obj->object_lt_y = $objY;
$obj->object_width = $objWidth;
$obj->object_height = $objHeight;
$obj->image_id = $imageId;
$obj->type_id = $typeId;
if ($obj->save()) {
    $obj_id = $obj->object_id;
    $object = DB::table('objects')->where('object_id',$objectId)->get();
    $success = array('status' => 1,'message' => $type_name.'标记成功!','obj_id' => $obj_id,'object' => $object);
    return response()->json($success);
} else {
    $error = array('status' => 0,'message' => $type_name.'标记失败!');
    return response()->json($error);
}

结果是:

Object {status: 1, message: "眼睛标记成功!", obj_id: "A7313004-3B7D-56F2-602F-FC81D4A8F04F", object: Array[0]}

1 个答案:

答案 0 :(得分:0)

在我看来,您有$obj->save()的条件,但您实际上从未调用$obj->save();来保存条目。

$obj = new Object;
$obj->object_id = $objectId;
$obj->object_lt_x = $objX;
$obj->object_lt_y = $objY;
$obj->object_width = $objWidth;
$obj->object_height = $objHeight;
$obj->image_id = $imageId;
$obj->type_id = $typeId;
$obj->save();

if ($obj->save()) {
   $obj_id = $obj->object_id;
   $object = DB::table('objects')->where('object_id',$objectId)->get();
   $success = array('status' => 1,'message' => $type_name.'标记成功!','obj_id' => $obj_id,'object' => $object);
   return response()->json($success);
} else {
    $error = array('status' => 0,'message' => $type_name.'标记失败!');
    return response()->json($error);

}