It seems that everyone is asking how to convert Query\Builder to Eloquent\Builder. I need the opposite - I have a Model with some scopes defined which I create a query from. The result that it returns is an instance of my model. I want it to be a a plain object.
Fetching a model and the converting to an stdClass doesn't seem right to me.
Is this possible?
Yes. You can build up the query using the Eloquent query builder, but then you can actually execute the query using the base query builder, which will return stdClass objects.
Below is an example. Obviously you can chain all this stuff together into one line, but I broke it out into multiple lines to explain what's going on. Assume you have an active() scope on your User model:
// start an eloquent query but don't execute it yet
$query = User::active();
// add any other conditions...
// get the base builder for the eloquent builder
$baseQuery = $query->getQuery();
// will return a standard array of stdClass objects
$users = $baseQuery->get();
Another example to just return one object:
// will return a stdClass object
$user = User::active()->getQuery()->first();
Be aware, though, that you do lose Eloquent query functionality, such as relationships and eager loading.
For example:
$user = User::with('posts')->active()->getQuery()->get();
This will not run the query for the posts for the users, and the posts will not be attached to the stdClass objects returned.
Related
ErrorException:
stripos() expects parameter 1 to be string, object given
For the groupBy() call in the with() method
$user = User::with([
'pricelists' => function($query) {
$query->groupBy(function($var) {
return Carbon::parse($var->pivot->created_at)->format('m');
});
}
])->where('id', $id)->get();
I already saw a few posts talking about how to manage this problem and that it shall not be possible to use groupBy() in eloquent but I do not really understand why...
To be clear:
User and Pricelist model got a many-to-many relationship with the default timestamps() method. I am trying to get the downloaded pricelists grouped by their months they were downloaded from the current user.
After a few attempts I just deleted the above shown => function($query... statement from the with() method and just left the with(['pricelist']) to fetch all datasets and tried this:
$user->pricelists = $user->pricelists->groupBy(function($var) {
return Carbon::parse($var->pivot->created_at)->format('m');
});
return $user->pricelists;
And it works fine and returns an array with multiple arrays for each month... But returning it like this:
return $user;
returns just 1 array with all entries... I do not really get the sense behind it right now...
The two groupBy() method that you are using in the two code you provide are totally different methods.
The first groupBy() where you use it in the callback is actually being called by $query which is a query builder object. The groupBy() here is used to add SQL GROUP BY Statement into the query. And as per the documentation, it only take string variables as parameter.
The groupBy() in your second code is being called by $user->pricelists which is a laravel eloquent collection. The groupBy() method here is actually from the base collection class and is used to group the items inside the collection into multiple collections under the different key defined by the parameter passed to the function. Please read the documentation here.
For your case, the second groupBy() is the one you should be using since you plan to use a callback and will allow you to use more complicated logic.
I need to understand when/not to use get(); in Laravel 5.
PHP warning: Missing argument 1 for Illuminate\Support\Collection::get()
Google shows me answers to their issue but no one really explains when you should/not use it.
Example:
App\User::first()->timesheets->where('is_completed', true)->get(); // error
App\Timesheet::where('is_completed', true)->get(); // no error
Fix:
App\User::first()->timesheets()->where('is_completed', true)->get(); // no error
Noticed the timesheets() and not timesheets? Could I have a detail explanation for what is going on, please?
I'm coming from a Ruby background and my code is failing as I do not know when to use () or not.
I'll try to describe this as best I can, this () notation after a property returns an instance of a builder, let's take an example on relationships,
Say you have a User model that has a one-to-many relationship with Posts,
If you did it like this:
$user = App\User::first();
$user->posts();
This here will return a relationship instance because you appended the (), now when should you append the ()? you should do it whenever you want to chain other methods on it, for example:
$user->posts()->where('some query here')->first();
Now I will have a the one item I wanted.
And if I needed say all posts I can do this:
$user->posts;
or this
$user->posts()->latest()->get();
$user->posts()->all()->get();
So the key thing here is, whenever you want to chain methods onto an eloquent query use the (), if you just want to retrieve records or access properties directly on those records then do it like this:
$user->posts->title;
Well, ->timesheet returns a collection, where ->timesheet() returns a builder.
On a Collection you can use ->where(), and ->get('fieldname'), but no ->get().
The ->get() method can be used on a builder though, but this will return a collection based on the builder.
Hope this helps.
The 'problem' you are facing is due to the feature of being able to query relations
When accessing a relation like a property, ->timesheets, the query defined in the relationship is executed and the result (in the form of a Collection) is returned to you.
When accessing it like a method, ->timesheets(), the query builder is returned instead of the resulting collection, allowing you to modify the query if you desire. Since it is then a Builder object, you need to call get() to get the actual result, which is not needed in the first case.
When you use ->timesheets you are accessing a variable, which returns the value of it (in this case an instance of Collection).
When you use ->timesheets() you are invoking whatever is assigned to the variable, which in this case returns an instance of Builder.
whilst pascalvgemert's answer does answer your problem regarding Laravel, it does not explain the difference between accessing or invoking a variable.
In simple term
$user = App\User::get();
is used to fetch multiple data from database
rather
$user = App\User::first();
is used to fetch single record from database
I would like to know if it's possible to return a MySQL stored procedure call as an eloquent object.
The below call works fine for me, but $result always returns an array instead of the usual Eloquent object.
$result = DB::select('call bookings_by_voucher()');
Does anyone know how to return this as an object, so that I can use ->count(), ->get() etc.
You must pass the array into a new instance of your eloquent object.
$booking = new Booking($result);
A late question, but if anyone else needs this:
Booking::fromQuery('call bookings_by_voucher()');
The only problem is you can't do further sql operations like where, limit, etc, since you can't manipulate a stored procedure directly, eg: you can't do "call bookings_by_voucher() where active = 1 limit 200". You can use laravel collection operations though.
https://laravel.com/docs/5.4/eloquent-collections
you can use eloquent MODEL. It return an object .
ex.
$user = app\ModelName::all()->count();
get(),count() and other aggregate function works with Models
I see you can call my MyModel::all() and then call "where" "groupBy" .. etc
I cant seem to find orderBy as this Q & A suggest..
Has this been removed in Laravel 5?
I've tried looking through the docs for a reference in Collection and Model but I'm assuming these are actually just modifiers for the collection returned and not actually modifying the query statement..
The only way I know of using order by is
\DB::table($table)->where($column)->orderBy($column);
Is that the only way to order your database select when executing a query?
You can actually just use it like where and groupBy:
$result = MyModel::orderBy('name', 'desc')->get();
Note that by calling MyModel::all() you're already executing the query.
In general you can pretty much use every method from the query builder documented here with Eloquent models. The reason for this is that the model proxies method calls (that it doesn't know) to a query builder instance:
public function __call($method, $parameters)
{
// irrelevant code omitted
$query = $this->newQuery();
return call_user_func_array(array($query, $method), $parameters);
}
$this->newQuery() creates an instance of the query builder which then is used to actually run the query. Then when the result is retrieved the model/collection is hydrated with the values from the database.
More info
Eloquent - Laravel 5 Docs
Illuminate\Database\Eloquent\Builder - API docs
And also the regular query builder (since quite a few calls get passed from the eloquent builder)
Illuminate\Database\Query\Builder - API docs
You can achieve this with the following solution:
$result = ModelName::orderBy('id', 'desc')->get();
You can do it by using sort keys
Model::all()->sortKeys()
(or)
Model::all()->sortKeysDesc()
Using Laravel 4.2 and eloquent ORM, I know that all multi-result sets returned by a query will return a Collection object, as documented here (http://laravel.com/docs/eloquent#collections).
I am running a query that returns a single object:
$faq = ProductFaq::where($where)->with('products')->get();
However, I'm being returned a collection.
In order to use the result do I need to chain ->first() to the end of my statement? I'm just confused if the docs are saying that every call that uses get() will return a collection, or only get() calls that have multiple results.
Get returns a Collection instance, you should call first instead of the get method
$faq = ProductFaq::where($where)->with('products')->first();