I have a strange issue. Here is the error message:
Call to undefined method MyProject\BlogBundle\Entity\Blog::findOneById()
I have setup the mapping, the entity class was created using the console and I have updated the schema in the database. What could be causing this issue?
I'm using symfony2. Here is the line:
$blogRepo = $this->get('myproject.blog.repository.blog');
$blog = $blogRepo->findOneById($id);
Any ideas?
findOneById doesn't exist, try
$blogRepo->findOneBy(array('id' => $id));
where 'id' is an existing field in your Entity.
You can check the Doctrine's class documentation here: EntityRepository
Edit: looks like findOneById does exist as long as the entity has a field "Id". Check the docs. Thx to Ryall for pointing it out
What is the service definition of myproject.blog.repository.blog? It looks like you are mapping it to MyProject\BlogBundle\Entity\Blog while it really should be MyProject\BlogBundle\Entity\BlogRepository.
Instead of creating your own Repository class you can also have one created on the fly by the EntityManager.
$user = $em->getRepository('MyProject\Domain\User')->find($id);
Or even shorter:
$user = $em->find('MyProject\Domain\User', $id);
Taken from the Doctrine2 ORM Documentation.
try this
$blogRepo = $this->getRepository('myproject.blog.repository.blog');
$blog = $blogRepo->findOneById($id);
getRepository
Related
I have foo an instance of the ember-data model thing. thing.js has the following property :
owner: DS.belongsTo('user')
If I have foo with an empty owner, how can I, with only foo and the 'owner' string, retrieve the value 'user' representing the model of the owner relation?
EDIT: I want to allow my select-relation component to works with relations where the name is different from the class name
It sounds like you have some work to do to finish setting up your relationships. Have a read through this page of the guides.
If the relationships are set up correctly, to get the associated user, you should be able to do foo.owner. This assumes that users are already present in the store. I recommend using the Ember Inspector browser plugin to debug the relationships.
This looks like a use case for typeForRelationship.
In your example you should be able to do something like
store.modelFor('thing').typeForRelationship('owner', store);
If you don't like that approach you can use the belongsTo reference API, where you use the meta data from the relationship to get the type
foo.belongsTo('owner').type
The only thing with that approach is that the type property may not be public API and possible (though unlikely) to change at some point.
It seems I can do the following :
this.get('model').get('_internalModel._relationships.initializedRelationships.'+this.get('relation')+'.relationshipMeta.type')
model being an instance and relation the string of the relation name, it correctly return the model of the relation.
EDIT : a better solution not using private API courtesy from the ember discord :
function getRelatedModelName(record, relationName){
let ParentModelClass = record.constructor;
let meta = get(ParentModelClass, 'relationshipsByName').get(relationName);
return meta.type;
}
I have problem with update entity with relations (one to many, many to one). I trying to add some new element to ArrayCollection when update, but nothing to do.
Here is my code of create and add relation:
$auctionPhoto = new AuctionPhoto();
$auctionPhoto->setAuction($auction);
$auctionPhoto->setPath($path);
$auction->getPhotos()->add($auctionPhoto);
All is running by doctrine entity listener (preUptade). The same code is do when I create entity (prePersist), but then is works fine.
I debug this and before persist I have in Auction object right relations, but nothing save to database.
Why do you do $auction->getPhotos()->add($auctionPhoto) ?
You should have a method addPhoto() or addAuctionPhoto() in your Auction entity, and use it like this:
$auction->addPhoto($auctionPhoto) or $auction->addAuctionPhoto($auctionPhoto)
EDIT:
Maybe your entity Auction is not the owner of the relation between the two entities, then you need to add $auctionPhoto->setAuction($auction), or if it's ManyToMany relation, then add $auctionPhoto->addAuction($auction)
Replace $auction->getPhotos()->add($auctionPhoto); with $auction->addPhoto($auctionPhoto);.
In your Auction entity, define the new method
// Auction.php
public function addPhoto(AuctionPhoto $thePhoto)
{
$this->photos[] = $thePhoto; // Add the photo to the object
$thePhoto->setAuction($this); // AuctionPhoto entity need to know about the reference
return $this; // Just for method chaining
}
(I assume $photos is your ArrayCollection which contains auction's photos)
Basically what you missed is to give a reference back to your entity:
$thePhoto->setAuction($this);
Are you saying nothing is in the database before you run this:
$em->persist($auction);
$em->flush();
If so, that is correct functionality. You need to persist then flush, then data is stored.
I'm fairly new to django web development. And I got an error whereby I try to change a 'post' under admin url - so localhost:8080/admin. I'm able to create it successfully but when I try to click the post that I had just added. I'm getting this error:
Exception Type: DatabaseError Exception Value: This query is not
supported by the database.
And this is the code that I know is 'messing' with this query:
#Post is an abstract class
class BlogPost(Post):
...
translators = models.ManyToManyField(Staff, related_name='translators')
photographers = models.ManyToManyField(Staff, related_name='photographers')
authors = models.ManyToManyField(Staff, related_name='authors')
...
To explain what is going on with this blog post - it can have multiple 'owners'/people that contributed to this post and thus the decision using ManyToManyField. And vice-versa with the 'Staff' member - the type of 'member' can have multiple ownership on multiple posts (Let me know if this logic doesn't make any sense because it does to me).
I'm using mongodb for the database, django 1.5.11 and I have installed djangotoolbox. I've tried the following solutions with adding a relationship to BlogPost as shown below:
Class Staff(Member):
...
staff_posts = models.ManyToManyField(BlogPost, related_name="staff_posts")
...
But I'm getting an error on 'cannot import BlogPost'. I tried figuring out the reason of this error and I don't think that I have a circular dependance - after checking all of the files, there's no circular dependance.
MongoDB (or mongoengine, which I'm guessing you're using) doesn't support joins, so the typical way to model many-to-many relations in a relational database has to be implemented some other way.
One way is to use a ReferenceField inside a ListField. It might look like this (not tested):
class BlogPost(Post):
authors = models.ListField(models.ReferenceField(Staff))
...
Also see these answers:
https://stackoverflow.com/a/18747306/98057
https://stackoverflow.com/a/25568877/98057
Just to put it out there, I'm not real familiar with MongoDB.
However, I don't believe you need to define a ManyToManyField on your Staff class. You already have a ManyToMany defined in your BlogPost, having it defined in one class file is all that is required. (At least for MySQL).
I am facing trouble using doctrine join. I can't share my code. But I can tell you scenario.
Please help me to achieve that.
I have created 2 entity. One User and Language.
User table is having foreign key language_id. and Language is master table with id and code fields.
I want to fetch user with some criteria, such a way it returns Language code from Language table as well.
I write join for that but it returns some full object...
Not sure how to fetch corresponding language code from Language table for language_id set in user table
If there is some example you know which can help me then also fine
i have return this in __construct()
$this->languageObj = new ArrayCollection();
when we print it is gives this
[languageObj:User:private] => Common\User\Entity\Language Object
(
[languageId:Language:private] => 1
[languageCode:Language:private] => en
[languageName:Language:private] => English
[languageCode2:Language:private] => User Object
RECURSION
)
I am not able to fetch languageCode from the object
You need methods defined in your entity to return the value from the object. It seems like everything is correct you would just need to grab the value from the entity. Here is an example:
$userEntity->getLanguageObj()->getLanguageId();
Your user Entity would need the getLanguageObj method which you can define like this:
public function getLanguageObj() {
return $this->languageObj;
}
And your Language Entity would also need a getLanguageId method:
public function getLanguageId() {
return $this->languageId;
}
Hope that helps!
I'd like to have access to one my model field verbose_name.
I can get it by the field indice like this
model._meta._fields()[2].verbose_name
but I need to get it dynamically. Ideally it would be something like this
model._meta._fields()['location_x'].verbose_name
I've looked at a few things but I just can't find it.
For Django < 1.10:
model._meta.get_field_by_name('location_x')[0].verbose_name
model._meta.get_field('location_x').verbose_name
For Django 1.11 and 2.0:
MyModel._meta.get_field('my_field_name').verbose_name
More info in the Django doc
The selected answer gives a proxy object which might look as below.
<django.utils.functional.__proxy__ object at 0x{SomeMemoryLocation}>
If anyone is seeing the same, you can find the string for the verbose name in the title() member function of the proxy object.
model._meta.get_field_by_name(header)[0].verbose_name.title()
A better way to write this would be:
model._meta.get_field(header).verbose_name.title()
where header will be the name of the field you are interested in. i.e., 'location-x' in OPs context.
NOTE: Developers of Django also feel that using get_field is better and thus have depreciated get_field_by_name in Django 1.10. Thus I would suggest using get_field no matter what version of Django you use.
model._meta.get_field_by_name('location_x')[0].verbose_name
You can also use:
Model.location_x.field.verbose_name
Model being the class name. I tested this on my Animal model:
Animal.sale_price.field.verbose_name
Animal.sale_price returns a DeferredAttribute, which has several meta data, like the verbose_name
Note: I'm using Django 3.1.5
If you want to iterate on all the fields you need to get the field:
for f in BotUser._meta.get_fields():
if hasattr(f, 'verbose_name'):
print(f.verbose_name)
# select fields for bulk_update : exclude primary key and relational
fieldsfields_to_update = []
for field_to_update in Model._meta.get_fields():
if not field_to_update.many_to_many and not field_to_update.many_to_one and not field_to_update.one_to_many and not field_to_update.one_to_one and not field_to_update.primary_key and not field_to_update.is_relation :
fields_to_update = fields_to_update + [field_to_update.name]
Model.objects.bulk_update(models_to_update , fields_to_update)