问题
I hate to be answering my own question, so maybe you can help me find what fixed this.
I have some eloquent models which belongTo each-other, and I set them up via association like this. It's all normal stuff.
This process unfortunately causes $device to work erratically. Below you can see individual values are accessible but any form of jsonification destroys the server without error.
$device = $truck->device;
if(is_null($device) || empty($device)) {
$device = new Devices;
}
$device->truck()->associate($truck);
$device->fleet()->associate($fleet);
$device->serial = $device_input['serial'];
$device->save();
$truck->device()->associate($device);
$truck->save();
error_log( $device->id ); //OK
error_log( $truck->device->id ); //OK
error_log( $device->toJson() ); //ERROR SEGMENTATION FAULT
error_log( $truck->toArray() ); //ERROR SEGMENTATION FAULT
error_log( $truck->device->toJson() ); //ERROR SEGMENTATION FAULT
error_log( $truck->device->toArray() ); //ERROR SEGMENTATION FAULT
error_log( json_encode($device) ); //ERROR SEGMENTATION FAULT
error_log( json_encode($truck->device) ); //ERROR SEGMENTATION FAULT
回答1:
Laravel isn't handling the error correctly.
First, check your table. When I printed my devices table I could see that new devices were being created every time I ran this, which means the associations were obviously not working.
I moved my associations inside the if statement like:
if(is_null($device) || empty($device)) {
$device = new Devices;
$device->truck()->associate($truck);
$device->fleet()->associate($fleet);
}
So that association would only happen when the device is created. You'd think setting the association to the object it's already associated to wouldn't break it.
And it's so weird that values are accessible individually but not as json. If anyone knows any laravel devs or a place to post this as an official bug report let me know
来源:https://stackoverflow.com/questions/31067642/laravel-5-eloquent-tojson-toarray-causes-strange-segmentation-faults