这段代码
FeesApplies::find(2)->toSql();
返回此查询
select * from `fees_applies`
为什么它忽略 id?
表中的主键没问题。 当我写的时候
FeesApplies::where('id',2);
一切正常
最佳答案
使用 Model::where('id', $value)
语法时,where
方法将返回 Illuminate\Database\Eloquent 类型的对象\生成器
。当使用语法 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());
要求模型实例再次查询数据库是一个全新的查询,而不是在您用于实际检索实例的上一个查询的基础上“构建”。
关于php - Laravel find 模型方法返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39125154/