我正在使用 Laravel 和 jQuery
将数据插入
到 MySQL
表中并取回新行的新 ID .问题是我得到一个空对象作为响应。我也尝试过 print_r
我的 Controller 中的结果,但我得到了一个巨大的数组。
这是一些代码。
jQuery :
$.ajax({
url: "locations/new",
type: "get", //send it through get method
data:{name:name,description:description},
success: function(response) {
$data = $(response);
console.log($data);
},
error: function() {
console.log("Unable add")
}
});
Controller :
$name= Input::has('name') ? Input::get('name') : null;
$description= Input::has('description') ? Input::get('description') : null;
$add = Location::add($name, $description);
return $add;
和我的模特:
public static function add($name,$description){
$location_id = DB::table('locations')->insertGetId(
array('name' => $name, 'description' => $description)
);
Self::get($location_id);
}
public static function get($location_id){
$result = DB::table('locations')->where('location_id',$location_id)
->select(DB::raw('location_id,name'));
$result->get();
return $result;
}
我知道我这里可能有误。请除了你的答案,我想知道错误的原因。
提前致谢..
最佳答案
在共同调查 (@chat) 之后,问题似乎出在查询构建器中。
添加 var_dump($result)
后输出为:
Error: Syntax error, unrecognized expression: object(Illuminate\Database\Query\Builder)#248 (27) { ["connection":prot
我建议删除 DB::raw
函数,因为您可以将字段传递给 select
函数,并且出于方便的原因,可以将 ->get() 函数附加到同一条线。所以最终的查询生成器代码将是:
$result = DB::table('locations')->where('location_id',$location_id)->select('location_id','name')->get();
这解决了问题。
更新 - 原因
在深入了解框架的源代码后,我发现:
/**
* Set the columns to be selected.
*
* @param array $columns
* @return $this
*/
public function select($columns = array('*'))
{
$this->columns = is_array($columns) ? $columns : func_get_args();
return $this;
}
所以 select
函数需要一个数组或参数作为 columns
,当 db::raw
被使用时 - 它返回了一个与 select
函数的预期参数冲突的字符串。
关于php - Laravel 中的 Ajax 请求返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181085/