How to split up an Eloquent model query

独自空忆成欢 提交于 2020-01-16 04:47:25

问题


I'm trying to break up an Eloquent query like this

$query = new Product;

if (!empty($req->query['id'])) {
    $query->where('id', '=', '1');
}

$products = $query->get();

The result above gives me all products in the database. This however, does in fact work.

$products = Product::where('id', '=', '1')->get();

Is there a way to do this?


回答1:


In Laravel 4 you need to append your query parameters to your query variable. In Laravel 3, it would work like you're doing.

This is what you need to do (I'm unsure if it will work with new Product tho):

$query = new Product;

if (!empty($req->query['id'])) {
    $query = $query->where('id', '=', '1');
}

$products = $query->get();



回答2:


Your code does not make sense. If you make a new Product - then it will never have an ID associated with it - so your if (!empty($req->query['id'])) will always be false.

Are you just trying to get a specific product idea?

$products = Product::find(1);

is the same as

$products = Product::where('id', '=', '1')->get();


来源:https://stackoverflow.com/questions/23852769/how-to-split-up-an-eloquent-model-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!