此代码
FeesApplies::find(2)->toSql();
返回这个查询
select * from `fees_applies`
为什么忽略id?
表中的主键可以。当我写
FeesApplies::where('id',2);
运行正常
使用Model::where('id', $value)
语法时,where
方法将返回一个类型为Illuminate'Database'Eloquent'Builder
的对象。当使用语法Model::find($value)
时,find
方法将返回一个Eloquent模型的实例。模型本身可以用于查询数据库,但是当试图将Eloquent实例直接转换为SQL而不添加任何其他条件(或使用返回Builder
对象的方法)时,实例将默认选择没有任何条件的所有记录。下面的脚本可以帮助您了解实际情况:
// $fees1 will be an instance of Illuminate'Database'Eloquent'Model
$fees1 = FeesApplies::find(2);
// Asking the model instance to convert itself to SQL without any conditions
var_dump($fees1->toSql());
// Asking the model instance to retrieve a Builder object with a single condition
var_dump($fees1->where('id', 2)->toSql());
请求模型实例再次查询数据库是一个全新的查询,而不是在您以前用于实际检索实例的查询上"构建"。
确保正确使用find()。在代码仍在运行时,很容易意外地使用first()导致不正确的结果。我们只是重构了where()来查找(),这导致了问题:
Model::find(1)->first();
这可能看起来是工作,但你实际上得到的是从表的第一行!
是返回错误的结果,还是sql查询错误?要查看查询运行情况,请尝试
DB::enableQueryLog();
FeesApplies::find(2);
dd(DB::getQueryLog());