Sorry for my bad english, I want to get a single row in my object. And I want that in random order. Im using array_rand() and it only return errors as stated below:
ErrorException: array_rand() expects parameter 1 to be array, object given in file C:\xampp\htdocs\user\TestProject\app\Http\Controllers\TestController.php on line
Here is my object.
"my_list": [
{
"id": 1,
"name": "My Name Test",
"address": [
{
"id": 1,
"city": "Manila",
"country": "Philippines"
}
]
},
{
"id": 2,
"name": "Your Name Test",
"address": [
{
"id": 2,
"city": "Cebu",
"country": "Philippines",
}
]
}
]
The problem is I want only to get a single row to the my_list which is object and not an array.
Here is my code.
$course = Course::where('id', 1)->with('my_list')->first();
$random_list = array_rand($course->my_list);
return $random_list;
I also try adding number of row in the array_rand like this.
$random_list = array_rand($course->my_list, 1);
But still not working.
What did I missed?
Any Eloquent query returns, by default, a Collection, even for the underlying relationships. Since you are working with one, this should work:
$course->my_list->random();
This will return only one item. If you want more, you could pass an argument to the random() method specifying the count of items you want.
For more information, check the documentation.
This Object is a Laravel collection. Please refer to the collection documentation.
https://laravel.com/docs/5.7/collections#method-random
You can try $course->my_list->random()
If you still wanna do this with your approach, can you try get_object_vars function to cast object into array.
$array = get_object_vars($object);
so that you can use them as an array in array_rand.
You might get an error, hence that it's an multi-dimensional array. Let me know so i may update.
Update for multidimensional:
Please refer to this.
// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);
try this:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder();
}])->first();
return $course->my_list;
Try this method:
$course = Course::where('id', 1)
->with(['my_list' => function($query) {
$query->inRandomOrder()->first();
}])->first();
return $course->my_list;
this method is more efficient since you will only get 1 row from my_list not like when you use $course->my_list->random() which retrieves all data and from there select a random row.
$random_list = $course['my_list']->random(number);
ps: number = number of element you want to get ,
Related
To make it easier to understand the problem, I will hardcode the data that I am using the collection on and explain the problem.
Let us assume the following data structure in JSON format,
{
"shelters_with_linear_distances": [
{
"id": 3,
"shelterName": "Third Shelter",
"latitude": "5.0034000",
"longitude": "70.1230000",
"linear_distance": 3.1352984845527
},
{
"id": 4,
"shelterName": "Fourth Shelter",
"latitude": "5.1413000",
"longitude": "70.2250000",
"linear_distance": 2.7850629146201
},
{
"id": 5,
"shelterName": "Fifth Shelter",
"latitude": "5.2220000",
"longitude": "70.1320000",
"linear_distance": 2.6042789457753
}
]
}
The following filter method is run on a collection format of 'shelters_with_linear_distance' in the above data structure and $minimum_distance_to_a_shelter is a dynamically calculated value that holds a data type of double.
$nearest_shelter = $shelters_with_linear_distances_from_user
->filter(function ($shelter, $key) use ($minimum_distance_to_a_shelter) {
return $shelter['linear_distance'] == $minimum_distance_to_a_shelter;
});
The problem here is if I send back the value returned by the filter method (which is the $nearest_shelter) as JSON to the frontend,
in the postman I see the following output,
{
"nearest_shelter": {
"2": { // <------------------------------------ I can not figure out from where this key '2' is coming from.
"id": 5,
"shelterName": "Fifth Shelter",
"latitude": "5.2220000",
"longitude": "70.1320000",
"linear_distance": 2.6042789457753
}
}
}
The problem is I can not figure out from where the key I have pointed with an arrow in the above line of code is coming from.
*) It is okay if that value '2' never changes so that in the later parts of code I can always access the $nearest_shelter as $nearest_shelter['2']. But the problem is, the value of that key changes depending on the data I am receiving from the db.
One time that value of the key was '1', then once I added some new records to the db it was '2'. Also this one other time there was no key marked as either '1' or '2' and the shelter I wanted was directly inside the collection.
Can someone please help me understand why this is happening and how to get rid of that since I want to access the value inside the $nearest_shelter in latter parts of the code and I do not want to get a key like that which I do not know the value of beforehand to access the $nearest_shelter later in the code.
(Project I am working on uses laravel 5.2)
Thanks.
When you filter a collection, the index is preserved.
The "2" is because this element was the third (so index 2) in your original collection.
To fix this, just add ->values() after the filter:
$nearest_shelter = $shelters_with_linear_distances_from_user
->filter(function ($shelter, $key) use ($minimum_distance_to_a_shelter) {
return $shelter['linear_distance'] == $minimum_distance_to_a_shelter;
})->values();
This way the index will be reset and will start from 0, as usual.
From the documentation (for Laravel 5.2 as stated in your question) documentation:
The values method returns a new collection with the keys reset to consecutive integers
In the current application, there is a model Part and a model Supplier. Every Part has a Supplier.
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
I added an accessor to get the name of the supplier.
If i return the whole dataset, i get the supplier:
public function getSupplierNameAttribute()
{
return $this->supplier;
}
"supplierName": {
"id": 1,
"uuid": "37e3a715-09d3-4fac-ae88-8f12e63fe79c",
"name": "Laserteam",
"street": "8602 Dessie Tunnel",
"zip": "15869",
"city": "New Clementview",
"email_send_type": null,
"active": 0,
"created_at": "2020-01-09 09:46:02",
"updated_at": "2020-01-09 09:46:02",
"deleted_at": null,
"action": "",
"activeLabel": "<span class='badge badge-secondary'>Inaktiv<\/span>"
},
If i try to get only the name (what I need finally), there is an error:
public function getSupplierNameAttribute()
{
return $this->supplier->name;
}
ErrorException: Trying to get property 'name' of non-object in file /gopanel/sites/7industry_net/public/7time/app/Models/Part/PartAttribute.php on line 48
If i try in this way, it works:
public function getSupplierNameAttribute()
{
return $this->supplier['name'];
}
Why does return $this->supplier->name; not work?
It's hard to say what could be the problem here, but:
Make sure you don't have supplier in casts for your model
Make sure you don't use supplier for database column name or you don't make somewhere something this
$this->supplier = $this->supplier->toArray();
It seems supplier property somewhere becomes array that's why one notation works but the other doesn't.
I’m not really sure what’s going on there; if you have a supplier relation then accessing the property should lazy-load the relationship.
Alternatively, you could try this syntax:
public function getSupplierNameAttribute()
{
$this->loadMissing('supplier');
return $this->getRelation('supplier')->name;
}
However, I’d avoid defining accessors like this. It can lead to N+1 problems if you say, retrieve a collection of parts and then call $part->supplier_name on each one without eager-loading the supplier relationship.
Personally, if I’m accessing attributing on relations that I prefer to do it through the relation (i.e. $part->supplier->name) so any relations I need to eager load are shown to me.
Try this code
public function getSupplierNameAttribute()
{
return $this->supplier->name ?? 'supplier not exists';
}
RethinkDB newb here and I can't figure this one out.
Lets say I have a table named mydata with documents that have the following basic structure:
{
"SomeAttirbute": "SomeValue",
"team": [
{
"name": "john" ,
"other": "stuff",
} ,
{
"name": "jane" ,
"other": "junk",
}
] ,
...
}
How do I get all documents in the mydata table that have john for a value of the name attribute for any of the elements in the team array?
This is pretty easy and requires a simple ReQL expression. In JavaScript it would be something like this:
const name = 'john';
...
r.db('q50732045')
.table('mydata')
// The predicate below can be literally read as:
// a document whose `team` property is a sequence
// that contains any element with a property `name`
// that equals the given name
.filter(doc => doc('team').contains(member => member('name').eq(name)))
// No need to invoke the run method in Data Explorer
;
I do believe it can be easily re-written in Python.
I think this is what you are looking for:
r.db(insert_database_name).table("mydata").filter(
lambda doc: doc["team"]["name"].contains("john")
).run(con)
or:
r.db(insert_database_name).table("mydata").filter(
r.row["team"]["name"].contains("john")
).run(con)
I have 2 tables say abc and xyz with ManyToMany relationship built over another table say abc_xyz (whose data will be returned as pivot key). However, pivot key upon retrieval has abc_id and xyz_id in return. I am able to access other columns in from abc_xyz table using method withPivot('dummy')
But, I want to hide the abc_id and xyz_id from the response. How do I do that?
I can hide the entire pivot key by using $hidden array but I want to hide only specific columns not the entire key.
Current Response
{
"abc_uuid": "some uuid",
"xyz" : [
{
"xyz_uuid": "some uuid",
"pivot": {
"abc_id": 1,
"xyz_id": 1,
"dummy" : "dummy value"
}
},
{
"xyz_uuid": "some uuid",
"pivot": {
"abc_id": 1,
"xyz_id": 2,
"dummy" : "dummy value"
}
}
]
}
So, I need only dummy from the pivot key, and hide abc_id and xyz_id. How do I do that?
Found a crude way to get this done. Found this answer in laravel issues unable to find the link now. However, it asks me to just add a method in my model and unset the keys I do not want.
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
foreach($attributes['xyz'] as $key => $value) {
unset($value['pivot']['abc_id']);
unset($value['pivot']['xyz_id']);
$attributes['xyz'][$key] = $value;
}
return $attributes;
}
this unsets the unwanted keys from my response. I hope laravel gives out an easy way for this.
Hello i am posting the id of several items along with their quantities to my server eg.:
[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]
Now on my server I need to validate each of these ids and get certain values from their respective rows in my database table.
What i simply want to do is this:
foreach ($items as $item)
{
$row = Items::find($item);
$price = $row->price;
}
But here i am wondering if the foreach loop will have a huge impact on speed and performance since the items may be many.
My question is is there a way of doing this in laravel without using a foreach, loop, like a query that can fetch data based on an array of ids.
If you want to take all the price attributes of certain ids you can use query's builder whereIn method to achieve this.whereIn accepts an array of values and returns the rows corresponding to these values.It's also very cost efficient when it comes to performance
I see you are passing a json string, so if you where to use whereIn one solution might be like the following:
Example
//json string
$json = '[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]';
//convert json to array
$json_toArray = json_decode($json,true);
//get id values from array
//If you are using php 5.5+ this will work, if you are using an older version you can use
//array_map method like this: $array_ids = array_map(function ($array) {return $array['id'];}, $json_toArray);
$array_ids = array_column($json_toArray, 'id');
//Finally execute the query
//Using Eloquent
$result = Items::whereIn('id', $array_ids)->select('price')->get();
//Using the Query Builder
$result = DB::table('items')->whereIn('id',$array_ids)->select('price')->get();