Laravel 5: Can't get model property in relationship - properties

I have a relationship in my model that requires a where condition:
public function characters() {
return $this->hasMany('Character')->where('characters.game_id', $this->game_id);
}
The problem is that "$this->game_id" doesn't appear to work. If I hard code the ID I need in its place, then the relationship works fine. I've also tried "$this->attributes['game_id']", which doesn't work either. I know that the value for "$this->game_id" exists, because I can view it when I return it in an accessor or as just a normal property in the resulting object. But for whatever reason, I can't access this value in the relationship. Thoughts?

Why do you require that particular where clause? I think hasMany does that for you.

Related

Eloquent relationship causes model nesting

I have the Eloquent BfsImages model defined with the following relationship:
public function listing()
{
return $this->belongsTo('App\CommercialPeople\Models\BfsListings', 'bfs_listing_id', 'bfs_listing_id');
}
And the attribute appended:
public function getPathAttribute()
{
return config('settings.bfs_image_path') . $this->listing->auth_agent_id . '/' . $this->filename;
}
As you can see the attribute refers to the parent model, so when I call the following:
BfsListings::with('images')->all();
Even though technically the relationship from images to listings is not called, because of that reference in the custom attribute BfsListing model is appended to images which causes model nesting so I get BfsListing->BfsImages->BfsListing.
My question is, is there a way to refer to parent model without actually appending it and returning it's data? Or.. perhaps there is a better way to maybe pass a variable from the parent to the child so that it could be used without calling the relationship back again?
To be honest since all my models are cached I don't care that much about multiple queries back and forth, I just want to remove the unnecessary data from images model, however I could use some smart way around it to not duplicate the query.
Edit
its possible to refer to other models without using the relations like this:
$this->listing()->setEagerLoads([])->first()->auth_agent_id;
However this still means that the reference to the parent model will be made once, which again causes two level nesting (so basically problem is not solved, but in some cases this will help to avoid infinite loops).
I still can't figure out how to call the parent model without actually loading it again.
You can alias the parent -> child relationship then access the parent via the alias.
$a = $parent->child;
$b = $a->parent;

Yii CActiveRecord with Column Named "attributes"

I used the CRUD generator from a legacy database. When searching for a column value I get the following error:
htmlspecialchars() expects parameter 1 to be string, array given (/usr/local/share/yii/framework/web/helpers/CHtml.php:103)
The problem is that the model has an existing column named "attributes" which is creating a conflict. I removed the entry from the _search.php and commented out all instances in the model hoping to at least get it working but no luck. Any suggestions would be appreciated.
Thanks.
Every CActiveRecord instance (or CModel instance for that matter) has a getter/setter named attributes with which all the attributes can be set. This leads to a conflict because the generated crud code uses the attributes attribute expecting it works as described before.
The controller does something like:
$model->attributes=$_POST['ModelClassName'];
// or
$model->attributes=$_GET['ModelClassName'];
This is meant to set al the (safe) attributes of the model at once. Instead this overwrites the database attribute attributes of your legacy DB model.
This in turn leads to the error you describe, because $_GET['ModelClassName'] and $_POST['ModelClassName'] typically contain arrays of data.
I guess the easiest fix would be to directly call the setter function for the "normal" attributes behavior which would lead to replacing the lines mentioned above with something like the following:
// in the controller
$model->setAttributes($_POST['ModelClassName']);
// and
$model->setAttributes($_GET['ModelClassName']);
I think rest of the generated CRUD code (the views) could and should be left untouched to make it work.
If you want to know how and why this works, it's best to do some research into the __get and __set magic functions and how they're used in the yii framework.

NHibernate: projecting a subclass type of an entity

How do I query a class of a specific entity in NHibernate?
I basically want a projection that returns a System.Type of each row that matches criteria.
I have looked at Get subclass type from projection with NHibernate however when I create Projections.Property("alias.class") or Projections.Property("class"), I always get could not resolve property 'class'.
Projections.Property("class") is possible and it works, but only if the class has a discriminator.
I got an answer from person on my team (Denis Bykov).
Unfortunately I had hard time making him answer here so I can award him reputation.
I don't think this is possible using NHibernate directly; but consider adding the following to your base entity class (assuming you have one):
protected virtual Type GetTypeUnproxied() {
return GetType();
}
After you have queried your entities, you can interrogate this property to return the actual CLR type of the entity.
If you can't get access to the type through NHibernate for projection purposes, perhaps you can store the System.Type in a field using a custom user type. This should give you the exact functionality you require.

NHibernate: How to check if an entity is persistent

I find myself writing code like the following quite a lot:
if (myEntity.Id == default(Guid))
Session.Save(myEntity);
What is the best way to check if an entity is already persistent (and therefore doesnt need to be saved)?
Am I doing something wrong writing code like this?
That's what I do except I usually use an IsNew() or IsTransient() method in a base class or extension that performs this check. Then the code becomes:
public Boolean IsTransient(){
return this.Id == default(Guid);
}
Don't forget that the Session.SaveOrUpdate(entity) method will cause an update of a persisted entity (as opposed to an insert) so you could use this method and ignore the check. I prefer to do the check though.

NHibernate - Changing sub-types

How do you go about changing the subtype of a row in NHibernate? For example if I have a Customer entity and a subclass of TierOneCustomer, I have a case where I need to change a Customer to a TierOneCustomer but the TierOneCustomer should have the same Id (PK) as the original Customer entity.
The mapping looks something like this:
<class name="Customer" table="SiteCustomer" discriminator-value="C">
<id name="Id" column="Id" type="Int64">
<generator class="identity" />
</id>
<discriminator column="CustomerType" />
... properties snipped ...
<subclass name="TierOneCustomer" discriminator-value="P">
... more properties ...
</subclass>
</class>
I'm using the one-table per class hierarchy model, so using plain-sql, it'd be just a matter of a sql update of the discriminator (CustomerType) and set the appropriate columns relevant for the type. I can't find the solution in NHibernate, so would appreciate any pointers.
I'm also thinking whether the model is correct considering this use-case, but before I go down that route, I want to make sure doing as described above is actually possible in the first place. If not, I'll almost certainly think about changing the model.
Short answer is yes, you can change the discriminator value for the particular row(s) using native SQL.
However, I don't think NHibernate is intended to work this way, since the discriminator is generally "invisible" to the Java layer, where its value is supposed to be set initially according to the class of the persisted object and never changed.
I recommend looking into a cleaner approach. From the standpoint of the object model, you're trying to convert a superclass object into one of its subclass types while not changing the identity of its persisted instance, and that's where the conflict is (the converted object isn't really supposed to be the same thing). Two alternative approaches are:
Create a new instance of TierOneCustomer based on the information in the original Customer object, then delete the original object. If you were relying on the Customer's Primary Key for retrieval, you'll need to take note of the new PK.
or
Change your approach so the object type (discriminator) doesn't need to change. Instead of relying on a subclass to distinguish TierOneCustomer from Customer, you can use a property that you can modify freely at any time, i.e. Customer.Tier = 1.
Here are some related discussions on the Hibernate Forums that may be of interest:
Can we update the discriminator column in Hibernate
Table-per-Class Problem: Discriminator and Property
Converting a persisted instance into a subclass
You're doing something wrong.
What you are trying to do is to change the type of an object. You can't do that in .NET or in Java. That simply doesn't make sense. An object is of exactly one concrete type, and its concrete type cannot be changed from the time the object is created until the time the object is destroyed (black magic notwithstanding). In order to accomplish what you are trying to do, but with the class hierarchy you laid out, you would have to destroy the customer object which you want to turn into a tier-one customer object, create a new tier-one customer object, and copy all the relevant properties from the customer object to the tier-one customer object. That is how you do it with objects, in object-oriented languages, with your class hierarchy.
Obviously, the class hierarchy you have isn't working for you. You don't destroy customers in real life when they become tier-one customers! So don't do it with objects either. Instead, come up with a class hierarchy that makes sense, given the scenarios you need to implement. Your use scenarios include:
A customer who previously is not tier-one status now becomes tier-one status.
That means you need a class hierarchy which can accurately capture this scenario. As a hint, you should favor composition over inheritance. That means, it may be a better idea to have a property named IsTierOne, or a property named DiscountStrategy, etc., depending on what works best.
The entire purpose of NHibernate (and Hibernate for Java) is to make the database invisible. To allow you to work with objects natively, with the database magically there behind the scenes to make your objects persistent. NHibernate will let you work with the database natively, but that's not the type of scenario which NHibernate is built for.
This is REALLY late, but may be of use to the next person looking to do something similar:
While the other answers are correct that you shouldn't change the discriminator in most cases, you can do it purely within the scope of NH (no native SQL), with some clever use of mapped properties. Here's the gist of it using FluentNH:
public enum CustomerType //not sure it's needed
{
Customer,
TierOneCustomer
}
public class Customer
{
//You should be able to use the Type name instead,
//but I know this enum-based approach works
public virtual CustomerType Type
{
get {return CustomerType.Customer;}
set {} //small code smell; setter exists, no error, but it doesn't do anything.
}
...
}
public class TierOneCustomer:Customer
{
public override CustomerType Type {get {return CustomerType.TierOneCustomer;} set{}}
...
}
public class CustomerMap:ClassMap<Customer>
{
public CustomerMap()
{
...
DiscriminateSubClassesOnColumn<string>("CustomerType");
DiscriminatorValue(CustomerType.Customer.ToString());
//here's the magic; make the discriminator updatable
//"Not.Insert()" is required to prevent the discriminator column
//showing up twice in an insert statement
Map(x => x.Type).Column("CustomerType").Update().Not.Insert();
}
}
public class TierOneCustomerMap:SubclassMap<TierOneCustomer>
{
public CustomerMap()
{
//same idea, different discriminator value
...
DiscriminatorValue(CustomerType.TierOneCustomer.ToString());
...
}
}
The end result is that the discriminator value is specified for inserts, and used to determine the instantiated type on retrieval, but then if a record of a different subtype with the same Id is saved (as if the record was cloned or un-bound from the UI to a new type), the discriminator value is updated on the existing record with that ID as an object property, so that future retrievals of that type are as the new object. The setter is required on the properties because AFAIK NHibernate can't be told that a property is read-only (and thus "write-only" to the DB); in NHibernate's world, if you write something to the DB, why wouldn't you want it back?
I used this pattern recently to allow users to change the basic type of a "tour", which is in reality a set of rules governing the scheduling of the actual "tour" (a single digital "visit" to a client's on-site equipment to ensure it all works properly). While they're all "tour schedules" and need to be collectable in lists/queues etc as such, the different types of schedules require very different data and very different processing, calling for a similar data structure as the OP has. I therefore completely understand the OP's desire to treat a TierOneCustomer in a substantially different way while minimizing the effect at the data layer, so, here ya go.
If you're doing it offline (e.g. in a DB upgrade script), just use SQL and ensure consistency yourself.
If this is something you plan will happen in while the app is running, I think your requirements are wrong, just like keeping the same pointer address for a different object is wrong.
If you save the ID and use it to access the customer again (e.g. in a URL) consider making a new field that contains a token for this that will be the business key. Since it's not the ID, it's easy to create a new entity instance and copy over the token (you'll probably need to remove the token from the old one).