Laravel - Table::find($is) 的奇怪行为,它是 returns 行数组,而不是 1 行
Laravel - Strange behaviour of Table::find($id), it returns array of rows, instead of 1 row
我怎么理解Table::find($id)应该等同于Table::where('id',$id)->first(),
但我收到数组而不是 1 条记录..
Order.php(型号):
public function change_user($order_id, $user_id) {
$order = Order::find($order_id);
dd($order);
if ($order == null) return false;
$order->user = $user_id;
return $order->save();
}
和 dd 的结果:
Collection {#270 ▼
#items: array:1 [▼
0 => Order {#271 ▼
+timestamps: true
#guarded: array:1 [▶]
#hidden: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:30 [▶]
#original: array:30 [▶]
#relations: []
#visible: []
#appends: []
#fillable: []
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
如果我错误地认为 find 应该 return 1 行,我仍然对此有疑问,因为当我删除 dd() 时收到错误消息:
BadMethodCallException in Macroable.php line 81: Method save does not exist.
in Macroable.php line 81
at Collection->__call('save', array()) in Order.php line 64
at Collection->save() in Order.php line 64
at Order->change_user(array('57'), '18') in RegistersUsers.php line 69
at AuthController->register(object(Request), object(Order))
at call_user_func_array(array(object(AuthController), 'register'), array(object(Request), object(Order))) in Controller.php line 76
您是否更改了主键?
检查 $id 是否不是数组。如果是数组,Laravel returns多1行。
如果您将数组传递给 find
,它会 return 一个集合。
好像$order_id
是一个数组
我怎么理解Table::find($id)应该等同于Table::where('id',$id)->first(), 但我收到数组而不是 1 条记录..
Order.php(型号):
public function change_user($order_id, $user_id) {
$order = Order::find($order_id);
dd($order);
if ($order == null) return false;
$order->user = $user_id;
return $order->save();
}
和 dd 的结果:
Collection {#270 ▼
#items: array:1 [▼
0 => Order {#271 ▼
+timestamps: true
#guarded: array:1 [▶]
#hidden: array:2 [▶]
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:30 [▶]
#original: array:30 [▶]
#relations: []
#visible: []
#appends: []
#fillable: []
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
如果我错误地认为 find 应该 return 1 行,我仍然对此有疑问,因为当我删除 dd() 时收到错误消息:
BadMethodCallException in Macroable.php line 81: Method save does not exist.
in Macroable.php line 81
at Collection->__call('save', array()) in Order.php line 64
at Collection->save() in Order.php line 64
at Order->change_user(array('57'), '18') in RegistersUsers.php line 69
at AuthController->register(object(Request), object(Order))
at call_user_func_array(array(object(AuthController), 'register'), array(object(Request), object(Order))) in Controller.php line 76
您是否更改了主键?
检查 $id 是否不是数组。如果是数组,Laravel returns多1行。
如果您将数组传递给 find
,它会 return 一个集合。
好像$order_id
是一个数组