I have an object, Brand, and I want to print the id of this object.
I am getting the following error when doing return Sentry::getUser()->brand()->get()->id:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
However, if I remove the ->id part, I am getting the whole object just fine, including the id (return Sentry::getUser()->brand()->get())
What am I doing wrong?
You need to use:
return Sentry::getUser()->brand()->first()->id;
Otherwise, you end up with a collection of users (even though that collection may only contain one user).
it might be reserved in a framework you used. My guess s that every object of any kind is a default object-type object that has an id of its own. If possible change the "id" to brand_id or something like that.
If there is only one object and will always be one, you can use return Sentry::getUser()->brand()->first()->id. That retrieves a single object, while get () returns an array of objects even if there is only one match.
Related
I have this relations:
Exercise - Muscle
Every Exercies can be related to multiple muscles and every muscle can be related to many muscles.
So they are defined as a ManyToMany relation.
Now i want to query all the muscles related to a particular exercies.
I tried something like this:
$muscle = $muscleRepository->find(9);
$c = new Criteria();
$c->where(Criteria::expr()->in('muscles', [$muscle]));
$res = $er->matching($c);
dd($res->toArray());
But this gives me a notice "Notice: Trying to access array offset on value of type null".
The notices appears whenever I try to do something with the LazyLoadCollection that comes from the ->matching call.
I've tried var_dumping and echoing things but the result is the same, so dd is not to be blamed.
I also tried contains and memberOf operators but with no luck.
Now I got things working writing an ugly workaround for this which involves removing the criteria and applying a ->filter function on the LazyLoadCollection but I would really like to handle this using Criteria class which seems to be made for this specific purpose.
Any idea?
Thanks
This is by far the strangest thing i have seen in PHP, but there surely is some sort of explanation.
Using serialize() i am storing some objects. At a later point, i revive them using unserialize().
Today i discovered a problem with an object that has been unserialized. Picture this scenario:
object__product_bundle Object (
[collateralValue] =>
[collateralGroup] =>
)
Now imagine $obj to be an instance of object__product_bundle as shown above.
When i did:
$obj->collateralValue = 10;
And checked the object variables, i was shown:
object__product_bundle Object (
[collateralValue] => 10
[collateralGroup] => 10
)
Mindboggling!
I spent an hour smashing my head against the table, as this didn't make sense. But when i started using var_dump() on the object, before making changes to it, i saw this:
object(object__product_bundle)#28 (15) {
["collateralValue"] => &NULL
["collateralGroup"] => &NULL
}
Apparently these properties/variables were somehow linked. I researched &NULL and all i found was this question which told me i am dealing with some sort of references.
But how?
My object comes from a serialized string.
Now, taking a look at the serialized string i found this:
s:15:"collateralValue";N;s:15:"collateralGroup";R:15;
What is R:15 ?
Can it be the issue?
How can this problem be addressed and where does it come from?
EDIT
After digging deeper, i found the culprit.
Orientiation:
The objects (as described above) are stored into a property of another object, which is the item of a shop cart.
class shopCart {
public $storage;
}
$cart->storage[] = new shopCart_item();
class shopCart_item {
public $object;
}
$object is where the products (object__product_*) are stored.
Upon placing an order, with the aim of being repeated (subscription), this entire shopCart is stored into the database as a blob.
Whenever a subscription order is scheduled, an automated task then grabs the old shopCart and generates a new order from it.
And here i found the culprit - i added the properties (collateralValue etc.) later during development, but there had already been stored orders.
Now during debugging i found that this is where PHP starts creating references, although i do not understand why.
Simply put:
static public function generateOrderFromSubscription() {
[...]
$order = new object__webShop_order();
var_dump($subscription->cart); // <-- no references are in here at all
$order->cart = serialize($subscription->cart);
var_dump($order->cart); // <-- suddenly, here i have the references
}
Apparantely, i use __sleep() for each object__product_* - which returns those variable names (including collateralValue and so on).
The question now becomes then: Why does PHP create references, when it is dealing with new properties for objects that were asleep but whose structure has changed in the meantime?
Very confusing!
EDIT #2
Finally some hope.
My __sleep() function basically returned a hardcoded array of variable names, as there were a ton of others i never wanted to store in the database. This approach apparently led to the current problem described in this question.
I still do not know why PHP creates references for variables in objects that were awoken without having those variables at all, but with those variables being returned in __sleep().
The only sensible solution to me, seemed to be to adapt __sleep(). I now do this:
public function __sleep(){
$vars=array(
'dbId',
'title',
'articleId',
'price_per_unit',
);
if(isset($this->collateralValue))
$vars[]='collateralValue';
if(isset($this->collateralGroup))
$vars[]='collateralGroup';
}
This way, __sleep() will not return (any of those two new) variable names (collateralValue, collateralGroup) which are not in use in the current object.
Well let's analyse your serialized string:
s:15:"collateralValue";N;s:15:"collateralGroup";R:15;
First property (key):
s:15:"collateralValue"
s just means it is a string
15 is the size of the string
collateralValue is the string itself the value (And if you look the string is 15 characters long)
First property (value):
N
N just mean NULL
Second property (key):
s:15:"collateralGroup"
s just means it is a string
15 is the size of the string
collateralGroup is the string itself the value (And if you look the string is 15 characters long)
Second property (value):
R:15
R means reference
15 means to the 15 value. So here the 15 value is probably the property collateralValue, which means if you change the value of it it also changes the value of the collateralGroup property
For more information see: http://www.phpinternalsbook.com/classes_objects/serialization.html
I have a php object that has a key=>value with something like [ipAddress] = 'NULL'
and if I do:
if(isset($object->ipAddress)){
echo "I am set!!!";
}
It never echoes. because apparently it's not "Set." I was under them impression that it is set, because oft he word NULL.
Is there a away to get around this to say, you are set? with out actually giving it a value? I ask because I attempted to write a function like this: (Don't mind the debugging, its the debugging that lead me to this question)
private function checkForColumnInModelObject($modelObject, $column, $custom_name){
$relationship = array();
foreach($modelObject as $model){
if(isset($model->$column)){
$value_returned = $model->$column;
var_dump($column);
var_dump($custom_name);
var_dump($value_returned);
//$relationship[$custom_name] = $value_returned;
}
}
//return $this->toObj($relationship);
}
So what I am trying to do here is check for a column in a model object. Now you might be given an array of columns, which we walk through in a function that calls this one, and an array of different model objects. were trying to see if the model object has that column.
So for example:
Does equipmentModel have ipAddress Column? yes? fetch me the value.
and the way we do this is by saying "is the column on this model set". The problem is, we might have columns with NULL value ... hypothetically their set, their value is just null, but PHP's isset() is all like NO, you are not set.
Any ideas on how I could write this to keep the same logic, BUT allow values of null to pass through assuming that model has that particular column?
If you want to know if an object property exists, regardless of its value, you can use property_exists.
if (property_exists($model, $column) {
...
}
isset returns true whenever you do an assignment to some variable. When you do $somevar=NULL; (In this case it is an assignment), if(isset($somevar) { echo "Inside"; } , The "Inside" will never print. Since NULL is never considered a value.
I would like to know if there is some improvement on MongoCollection::findOne or if is just an "alias" or "shorcut" to MongoCollection::find with a limit of 1, for example.
Thank you
findOne() is an alias of find() with a limit(-1)
You can see this in the source code here. It does the equivalent to
find(...).limit(-1).getNext().
The -1 is actually relevant. Here's a snippet from the wire protocol docs:
If the number is negative, then the database will return that number
and close the cursor.
If you go to the shell and type > db.collection.findOne (no parens), you can see that the function is also just a helper in the shell.
So, "yes findOne() is just a helper".
From the mongo tutorials...
To show that the document we inserted in the previous step is there,
we can do a simple findOne() operation to get the first document in
the collection. This method returns a single document (rather than the
DBCursor that the find() operation returns), and it's useful for
things where there only is one document, or you are only interested in
the first. You don't have to deal with the cursor.
The MongoCollection::findOne method will directly return the result array and the MongoCollection::find one will return a MongoCursor instance even if it is a single valued result.
mongodb.org has an performance test report where they compared findOne and find. Based on the results it would seem that findOne is 35-45% faster.
Few data points from the report:
find_one (small, no index): 989 Ops/s
find (small, no index): 554 Ops/s
It is almost like an alias but instead of return you a list, it returns you an object.
It depends on your search query. E.g if you search by ID, since ID is unique it would not need to limit the results because only one result would be found. If more than one record is found then it would limit the results by 1. Another difference is that findOne returns an array, while find returns a mongoCursor.
this piece of code was given in a book.
$query="select name, description from widget where widgetid=$widgetid";
$rs=mysql_query($query,$this->connect);
if(!is_resource($rs))
throw new exception("could not execute the query");
if(!mysql_num_rows($rs))
throw new exception("found no rows");
$data=mysql_fetch_array($rs);
$this->name=data['name'];
$this->description['description'];
what is meant by the last two lines of the code?
The third line before the end :
$data=mysql_fetch_array($rs);
will fetch one row of the resultset that corresponds to the SQL query, and assign it, as an array, to $data.
See the documentation of mysql_fetch_array() for more details.
The next line :
$this->name=data['name'];
is not valid PHP, and will result in a Parse Error.
Instead, to be valid, it should be written like this :
$this->name=$data['name'];
Note the additionnal $, that means that $data is a variable.
It will assign the value of the name item of the $data array to the name attribute of the current object.
Basically : the name attribute of the current instance of your class will contain the value of the name column of the row you've fetched from database.
And, finally, the last line :
$this->description['description'];
doesn't do anything : you access the description item of the attribute description of the current object -- that attribute being an array ; but you don't do anything with it.
I suppose it should be written :
$this->description = $data['description'];
In which case it would do the same kind of thing as the previous line -- with the description item/field/attribute.
Considering your question, you should take a look at the PHP manual, and, especially, at the following sections :
Arrays
Objects
Classes and objects
$this refers to the current instance of the class.
-> tells PHP to refer to a member of the instance.
name is the referred member.
So, the following line:
$this->name = $data['name'];
Sets the property name of the current instance ($this) to whatever value held by the array $data at index name.
For more information, you can read the OOP Basics in the PHP Documentation:
PHP Documentation: Classes and Objects - The Basics
PHP Documentation: Classes and Objects - Properties
Well for starters, "data" is the array that hold the results of your query.
In your query you are retrieving "name" and "description" from the table "widget".
$this->name = data['name'] is assigning the value of name from the query to the name property or variable in your instance. $this refers to the current instance
Does that help?
Considering this code is from book, I think it is part of some method where widget name and description is fetched from DB and updated on class properties.
BTW, if last two lines are as is as you pasted then there is some print mistake :)