Laravel - Table :: find($ id)的奇怪行为,它返回行数,而不是1行

时间:2016-02-24 14:42:00

标签: php laravel laravel-5 laravel-5.2

我如何理解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
    }
  ]
}

如果我错了,查找应返回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

2 个答案:

答案 0 :(得分:2)

如果将数组传递给find,它将返回一个集合。

似乎$order_id是一个数组。

答案 1 :(得分:1)

您是否更改了主键?

检查$ id是否不是数组。如果它是一个数组,Laravel返回的行数超过1行。