![]() ![]() The workaround is to get all results into Collection and then get the keys: $allPermissions = Permission::all()->modelKeys() īut it may cause performance issues if you're getting all records for big table. protected primaryKey fooid the find() function will go through fooid instead of id. $permissions = $role->permissions->pluck('id') īut in case of modelKeys(), this will fail with error "Call to undefined method App\Models\Permission::modelKeys()": $allPermissions = Permission::modelKeys() The find() method finds the Model by its primaryKey property. So method pluck() exists for both Model and Collection, so both would work: $allPermissions = Permission::pluck('id') Notice that, as I said before, it works on Collections, not on just Laravel model. Official description of modelKeys() method is pretty short: "Get the array of primary keys." $permissionIDs = $role->permissions->modelKeys() $permissionIDs = $role->permissions->pluck('id') īut what if your auto-increment primary key name is not "id"? Apparently, you can get the key(s) from Laravel model, with method modelKeys() on Collection: // Same result as above. ![]() we will help you to give an example of how to get data with multiple ids in laravel eloquent. 'Composite' primary keys are not supported by Eloquent models. In this article, we will implement a laravel where multiple ids. One of those helpers come to rescue when you need to increment a column, basically run update X set YY+1 where id Z - apparently, there's no need to run update () function for that. Typical code to do this will be with pluck() function: // returns array of IDs Eloquent requires each model to have at least one uniquely identifying 'ID' that can serve as its primary key. And then you need to get IDs of permission by a certain role. ![]() Imagine, that you have hasMany() relationship - one Role has many Permissions. I will show you two quick ways to do it - one is pretty popular, and another is a function which I found out only today. There are situations where you need to get array of IDs for some records in collection/table. On further inspection I discovered that the above mentioned find() is a part of Illuminate\Database\Eloquent\Builder class. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |