试试这样:
Page::where('slug', '=', 'about')->firstOrFail();
// or without the explicit '='
Page::where('slug', 'about')->firstOrFail();
更新:我目前正在使用 Laravel 6.9.0,我确认 @jeff-puckett 是正确的。 Where 子句工作正常。这就是它在我的修补程序上的工作方式。
>>> \App\Models\User::findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> App\Models\User
id: "123b5545-5adc-4c59-9a27-00d035c1d212",
name: "John",
surname: "Graham",
email: "john.graham@test.com",
email_verified_at: "2020-01-03 16:01:53",
created_at: "2020-01-03 16:01:59",
updated_at: "2020-01-03 16:01:59",
deleted_at: null,
>>> \App\Models\User::where('name', 'Buraco')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> Illuminate/Database/Eloquent/ModelNotFoundException with message 'No query results for model [App/Models/User] 123b5545-5adc-4c59-9a27-00d035c1d212'
>>> \App\Models\User::where('name', 'John')->findOrFail('123b5545-5adc-4c59-9a27-00d035c1d212');
>>> App\Models\User
id: "123b5545-5adc-4c59-9a27-00d035c1d212",
name: "John",
surname: "Graham",
email: "john.graham@test.com",
email_verified_at: "2020-01-03 16:01:53",
created_at: "2020-01-03 16:01:59",
updated_at: "2020-01-03 16:01:59",
deleted_at: null,
过时:至少花了两个小时才意识到如果在 Laravel 5.6 中将 firstOrFail() 方法链接到 where() 之后,它基本上会尝试检索表的第一条记录并删除 where 子句。所以在 where 之前调用 firstOrFail。
Model::firstOrFail()->where('something', $value)
where
助手。我的意思是在数据库变成集合之前使用 where
子句查询数据库。
## Or Via Scope For Multiple Rows ##
public function scopeGetOrFail ($query)
{
if (empty($query->count())) {
abort(404);
} else {
return $query->get();
}
}
Page::whereSlug('about')->getOrFail();
Page::where("slug","about")->getOrFail();
在我看来,当您将静态 find() 用于 eloquent 模型时,也许您可以定义函数 getRouteKeyName() 以显式获取所需的列。
public function getRouteKeyName(){
return 'slug';
}
如果你坚持,你可以把它写成模型内部的静态函数
public static function findBySlugOrFail($value){
//get slug collection or return fail
return Post::where('slug', '=', $value)->firstOrFail();
}
试试这样:
Page::where('slug', '=', 'about')->get()
不定期副业成功案例分享
Page::where('about', 'data')->firstOrFail();
这应该适用于相等运算符 '=' 无需明确说明Page::whereAbout('data')->firstOrFail();