Is there any difference between these three:
someModel::where('id', 1)->first();
someModel::where('id', '=', 1)->first();
someModel::first()
what about these two?
someModel::skip(1)->take(4)->get();
someModel::where('id', '!=', 1)->take(4)->get();
.
I'm adding multitenancy to an existing product (single DB approach). I was wondering if I could simply replace all
where('id', 1)->first();
statements with
first();
?
CodePudding user response:
when you omit the operator, laravel will translate it as EQUAL
so these 3 have the same queries,
someModel::where('id', 1)->first();
//equals to
SELECT * FROM `somemodels` WHERE `id` = 1 LIMIT 1
someModel::where('id', '=', 1)->first();
//equals to
SELECT * FROM `somemodels` WHERE `id` = 1 LIMIT 1
someModel::find(1);
//equals to
SELECT * FROM `somemodels` WHERE `somemodels`.`id` = 1 LIMIT 1
while these last one has different query
someModel::first()
//equals to
SELECT * FROM `somemodels` LIMIT 1
and these are the queries of your additional question
someModel::skip(1)->take(4)->get();
//equals to
SELECT * FROM `somemodels` LIMIT 4 OFFSET 1
someModel::where('id', '!=', 1)->take(4)->get();
//equals to
SELECT * FROM `somemodels` WHERE `id` != 1 LIMIT 4
CodePudding user response:
These are same:
Model::where('id', 1)->first(); Model::where('id', '=', 1)->first();
But this may give you result if model with id 1 was deleted:
Model::first();
These are different:
Model::skip(1)->take(4)->get(); Model::where('id', '!=', 1)->take(4)->get();
In the first case, you will skip any model regardless of its ID. In the second case, you are excluding only model with ID 1.
No you can't, that's different queries. But you can replace
Model::where('id', 1)->first();
with
Model::find(1);