[英]Laravel using WHERE in eloquent ORM
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? 在Laravels雄辩的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 谢谢
'Yes, you can build dynamic where. '是的,你可以在哪里建立动态。 It's parse in simple where statement.
它在简单的where语句中进行解析。 Also you can build magic query like this:
你也可以像这样构建魔术查询:
$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();
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:具有查询范围的帖子模型,用于获取“status”=已发布的所有帖子。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.