Laravel Eloquent Model::find doesn't work

倖福魔咒の 提交于 2019-12-23 04:04:06

问题


This don't work:

$object = Model::find($id);

This works:

$object = Model::where('id', '=', $id)->first();

It doesn't make sense. Am I missing something? I'm using Laravel 5.2.36.


回答1:


id needs to be a primary key, see: https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_find




回答2:


I had the same problem. I sorted out it, using the function intval() to transform $id to an integer value:

$id = intval($id);
$object = Model::find($id);



回答3:


public $primaryKey  = 'id';

make it a primary key in your model file or you can use

Model::firstOrNew(['id' => $id]);

but here id should be a fillable property in the model. for example

protected $fillable = ['id'];


来源:https://stackoverflow.com/questions/37719932/laravel-eloquent-modelfind-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!