I am trying to loop through all the properties of the $entity variable on the beforeSave() method.
debug($entity) returns:
object(App\Model\Entity\Student) {
'id' => (int) 5690,
'institution_id' => (int) 35,
'contact_id' => null,
'id_number' => '0000000000',
....
However, when I try to look through the object, using
foreach ($entity as $key => $value) {
debug($key);
debug($value);
}
the foreach loop does not even run. I investigate by debug(count($entity)), and it returns 1.
How can I loop through the properties of my entity?
Any help is appreciated. Thank you.
To get a list of accessible and non-static properties of an object, use function get_object_vars.
I would also check if the $entity object is not actually an array containing a single entity object.
Related
I am using PHP 7.1.33 and Laravel Framework 5.8.36.
I am getting receiving data from a database row-by-row and I am creating a model using updateOrCreate() like the following:
foreach ($arr as $v) {
$product = new Product();
$product->name = $v['name'];
$product->url = $v['url'];
$product->price = $v['price'];
// save
$matchThese = ['name' => $name, 'url' => $url];
$product->updateOrCreate($matchThese);
}
However, nothing gets created.
Any suggestions what I am doing wrong?
I appreciate your replies!
updateOrCreate takes 2 parameters ($attributes, $values).
$attributes is an array containing key-value pairs which will basically be used for where clauses i.e. it will check the database for the attributes passed in this array.
$values is an array containing key-value pairs of what to update in the database.
If it can't find a row in the database matching the first array it will combine the values in the arrays to create a new row.
To achieve what you're after you can do:
Product::updateOrCreate(
['name' => $v['name'], 'url' => $v['url']],
['price' => $v['price']]
);
Try this way
Product::updateOrCreate(
['name' => $name, 'url' => $url],
['price' => v['price']],
)
First parameter is for search the register.
Second parameter set new values.
For more information, you can read Eloquent: Getting Started - Documentation
I am using PHP7.
I have an Object I am trying to parse:
$RECORD = {
'name' => 'Stephen Brad Taylor',
'address' => '432 Cranberry Hills, Pittsburg',
'phone' => '708 865 456',
'Account' => (Object Vendor/Entity/User) {
'email' => 'INeedThisEmail#pleaseHelp.com' // I want to access this property.
'id' => 34,
'accessible' => ['email', 'id]
}
}
I have an array which I am using to select certain fields from RECORD:
$fieldnames = [
'name',
'address',
'phone',
'Account["email"]'
];
I am trying to parse the fieldnames from RECORD as follows:
$data[]
foreach($fieldnames as $k => $fieldname) {
$data[k] = $RECORD->$fieldname
}
The method above works for the first-level attributes: name, address, and phone. However, email returns null.
I have tried the following below and none have worked:
$data[k] = RECORD->${$fieldname}
$propertyName = '$RECORD->$fieldname'
$data[k] = ${$propertyName}
Does anyone know a way to access an object's properties using a string from an object reference?
Much gratitude <3
You can't use Account["email"] directly as a property accessor, it won't be split up to find the nested property. You need to parse it yourself.
foreach($fieldnames as $k => $fieldname) {
if (preg_match('/^(.*)\["(.*)"\]$/', $fieldname, $match) {
$data[$k] = $RECORD->{$match[1]}->{$match[2]};
} else {
$data[$k] = $RECORD->$fieldname;
}
}
Also, you need $ in $k.
This code only works for 1 level deep. If you need to deal with arbitrary levels, you'll have to write a recursive procedure. See How to access and manipulate multi-dimensional array by key names / path? for examples of how to code this.
I use anonymous functions for such cases. (PHP 7.4)
$index = fn($item) => $item->dotaItem->prop_def_index;
if (get_class($collection) === Collection::class) {
$index = fn($item) => $item->prop_def_index;
}
I'm developing with DataTables in Laravel and trying to make an object manually using collect() to create a collection. When I push the collection into the DataTable, there is something wrong, and I can't call my object with this $object->attribute.
After I get the error with that, I already tried to call an attribute with $object['attribute'], and it works well.
Can someone give me insight about the differences and how I can convert $object['attribute'] into $object->attribute?
This is my query to create object
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]);
$result->push($item);
Accessing $object['attribute'] means $object is an array and accessing $object->attribute means $object is an object.
To convert array to object:
$object = (object) $object;
Additionally, to convert object to array:
$object = (array) $object;
DataTables calls internally toArray() on the collection items when you build the table. This happens during transformation of the data. It will also flatten nested objects (e.g. loaded Eloquent relations in case of an EloquentDataTable) into an array with depth 1 (per row of the table).
You can try the following way,
$result = collect();
$item = collect([
'row' => ($key+1),
'item_id' => $value->uid,
'item' => $value->nama_item,
'sub_kategori' => $value->sub_jenis_item->sub_jenis_item,
'kategori' => $value->jenis_item->jenis_item,
'gudang_id' => $id_gudang
]
);
$result->push($item);
$resultObj = json_decode($result);
foreach($resultObj as $obj){
echo $obj->row;
}
I am using Laravel, and I have a foreach function like this
$name = person::find(1);
foreach($name as $dbitems) {
$person->services()->updateOrCreate([
'service' => $dbitems->Name,
'time' => $dbitems->Time
'price' => $anotherarrayhere
]);
}
In the place of $anotherarrayhere, I want to get this array from the outside of foreach function.
$anotherarrayhere = $peopleserviceprice[]
How can I include the $anotherarrayhere variable in the above foreach function?
foreach is not a function, you can use variables from outside the loop without problems. Maybe you're confused with collection callbacks that needs to specific tell variables
Any way, you're iterating over a model, not a collection, since you're using find.
$person = person::find(1);
$person->services()->updateOrCreate([
'service' => $person->name,
'time' => $person->time
'price' => $anotherarrayhere
]);
This is my first question here, so please try to be patient with me :)
I've stumbled upon a weird behavior populating an object.
I started to convert the objectQuery::create()-> ... ->find() methods used in my project to $c = new Criteria(), $c-> ... objectPeer::doSelect($c) since I've been told Queries shouldn't be used when criteria can be.
I have a function, that returns all the prices of items from the shop. Or at least did. The thing that I cannot figure out is this:
the old code:
static public function shopGetPrices($id){
$prices = itemPriceQuery::create()->
addJoin(itemPricePeer::ITEM_ID, itemPeer::ID, Criteria::LEFT_JOIN)->
addJoin(itemPeer::CATEGORY_ID, categoryPeer::ID, Criteria::LEFT_JOIN)->
addJoin(categoryPeer::SHOP_ID, shopPeer::ID, Criteria::LEFT_JOIN)->
add(shopPeer::ID, $id)->find();
return $prices;
}
returns correctly populated PropelObjectCollection object, through which i can go with foreach, and get/set the itemPrice objects and attributes i need.
now, the new code:
static public function shopGetPrices($id){
$c = new Criteria();
$c->addJoin(itemPricePeer::ITEM_ID, itemPeer::ID, Criteria::LEFT_JOIN)->
addJoin(itemPeer::CATEGORY_ID, categoryPeer::ID, Criteria::LEFT_JOIN)->
addJoin(categoryPeer::SHOP_ID, shopPeer::ID, Criteria::LEFT_JOIN)->
add(shopPeer::ID, $id);
return self::DoSelect($c);
}
returns an array of itemPrice objects, but they are populated with item values related to itemPrice objects through join. that means : when I call print_r(self::DoSelect($c)); it prints
Array
(
[0] => ItemPrice Object
(
[startCopy:protected] =>
[id:protected] => 47 <- id of joined item
[item_id:protected] => 9 <-foreign key to category object of joined item
[price:protected] => 0
[unit:protected] => Axe <- name of item, not unit (unit is like 'golden', 'iron', 'wood' or whatever )
[active:protected] =>
[collItemsOrder:protected] =>
[collItemsOrderPartial:protected] =>
[alreadyInSave:protected] =>
[alreadyInValidation:protected] =>
[polozkyObjednavkasScheduledForDeletion:protected] =>
[prisadyPolozkyObjednavkasScheduledForDeletion:protected] =>
[validationFailures:protected] => Array()
[_new:protected] =>
[_deleted:protected] =>
[modifiedColumns:protected] => Array()
[virtualColumns:protected] => Array()
)
[1] => ItemPrice Object
(
...and so on.
There is probably some crucial difference between criteria and query object, that I'm missing. I searched on Google, StackOverflow, and who knows where, but I didn't find anything resembling a solution to this.
This guy/gal had a vaguely similar problem, but I didn't use addSelectColumn with my criteria, so it's been another dead end for me.
Can anyone please point me in the right direction?
I found the problem. It was that I had overriden method do select in itemPricePeer class
public static function doSelect(Criteria $criteria, PropelPDO $con = null){
$critcopy = clone $criteria;
$critcopy->add(self::ACTIVE, 1);
return self::populateObjects(itemPeer::doSelectStmt($critcopy, $con));
}
I switched self/itemPricePeer with itemPeer in populateObjects arguments. silly me :-/ Thanks for your responses anyway j0k.