Laravel 在雄辩的 ORM 中使用 WHERE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26995011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:26:59  来源:igfitidea点击:

Laravel using WHERE in eloquent ORM

phplaravelormeloquent

提问by user2722667

I came across this

我遇到了这个

$user = User::whereConfirmationCode($confirmation_code)->first();

In Laravels eloquent ORM, can you append the tables row name in the where statment like above?

在 Laravel eloquent ORM 中,你能像上面那样在 where 语句中附加表行名称吗?

Before I saw this I would just written

在我看到这个之前我只想写

eg: $user = User::where('confirmation_code', '=', $confirmation_code)->first();

例如: $user = User::where('confirmation_code', '=', $confirmation_code)->first();

Thanks

谢谢

回答by xAoc

'Yes, you can build dynamic where. It's parse in simple where statement. Also you can build magic query like this:

'是的,你可以在什么地方建动态。它在简单的 where 语句中解析。您也可以像这样构建魔术查询:

$user = User::whereConfirmationCodeAndIdOrRole(12345, 5, 'admin')->first();

It will be transform to:

它将转换为:

$user = User::where('confirmation_code', '=', 123456, 'and')->where('id', '=', 5, 'or')->where('role', '=', 'admin')->first();

回答by SamSquanch

I may be wrong. I was un-aware of magic query builder setup.

我可能是错的。我不知道魔术查询构建器设置。

That is a custom query scope.

这是一个自定义查询范围

IE: A post model with a query scope to get all posts with 'status' = published.

IE:具有查询范围的帖子模型,用于获取“状态”= 已发布的所有帖子。

class Post extends Eloquent {
    /**
     * Get all posts with 'status' published
     *
     * @param Illuminate\Database\Query\Builder $query
     * @return Builder $query
     */
     public function scopePublished(Builder $query)
     {
         return $query->where('status', 'published');
     }
}

Then using it:

然后使用它:

 Post::published()->first();

Note parameters can be passed to the custom scope by passing them as parameters to the query scope after the query builder.

注意参数可以通过将它们作为参数传递到查询构建器之后的查询范围来传递到自定义范围。

 public function scopeStatus(Builder $query, $status)
 {
     return $query->where('status', $status);
 }