Twig and Symfony2 - Entity was not found - php

I have an entity that is related to some other entities.
On the end, I have an object like tat:
paper.submission.authors
For some of the paper.submission, there is no author, and in my twig template, I am doing:
{% for author in paper.submission.authors}
do something
{% endfor %}
And for the paper.submission with no authors, I am getting "Entity was not found" exception.
Is thee any possibility to test if the object exists before my for loop.
I have try the is defined, it is always true. Then, I have tryed is not null, but this is also generating the exception.
Thank you very much in advance.

Problem
Doctrine throws this Exception when it doesn't find the related entity. It seems redundant to say this, but in fact this is important.
It means it could find an ID related to it, but the request doctrine made didn't match any result.
My guess is that your database table (link table actually) submission.authors contains IDs of 0 instead of NULL.
With such, Doctrine thinks there IS an author with ID of 0, and therefor, cannot find it.
What happens
submission.authors always exists. It is an Uninitialized Doctrine Proxy.
var_dump($submission->getAuthors());
Would show you what contains exactly submission.authors
At this point, no queries are made. It simply returns a PersistentCollection with a flag isInitialized to false.
The exception occurs when you're trying to get a property out of it
foreach ($submission->getAuthors() as $author) {
}
When doing this doctrine will check if getAuthors is initialized. If not, it will run the following query
SELECT <stuffs> FROM authors WHERE id = 0;
Which returns no match and will throw an EntityNotFound Exception
Fix
You must set your id row's default to NULL and make a query to update all 0's to NULL.
With this, you can easily test submission.authors with is not null
Doctrine will not run any query if it finds a NULL

How to debug to find which related entity was not found?
Exception message improved in repository https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Proxy/ProxyFactory.php#L160 but if you use older version you can do the following debugging.
If you use older version
Put following code to ProxyFactory class before throw new EntityNotFoundException(); line vendor/doctrine/orm/lib/Doctrine/ORM/Proxy/ProxyFactory.php:177
$entity = $classMetadata->getReflectionClass()->getShortName();
$id = $classMetadata->getIdentifierValues($proxy)['id'];
var_dump("$entity WHERE id = $id NOT FOUND.");exit;
throw new EntityNotFoundException();

In your entity you can made something like this:
public function getSubmission(){
if($this->Submission->getId()==0) return null;
return $this->Submission;
}

Related

Check If Model Exists

When searching for what should be a very basic and common test in Laravel, there seems to be much confusion on how to properly check weather or not a model exists and then do something with the model if it does. When searching through stackoverflow, laracasts, and the laravel documentation itself, it does not become anymore clear. If I for example run this query,
$restaurant = Restaurant::find($input["restaurant_id"]);
There are various stack overflow posts that would have me check the count(), use the exists() method which does not seem consistent, or use firstOrFail() which throws an exception. All I want to do is run a call like the one above, check if $restaurant is a valid model, and then do something if it is. There is no need for an exception in my case and I don't want to have to have to run the query again after using something like count() or exists(). The documentation has no useful information on this either which allows 4 different variable types to be returned without any mention of which case will trigger which return. Does anyone have a good handle on this topic?
Laravel checking if record exists
Eloquent ->first() if ->exists()
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_find
You don't need to run any additional queries. If the record does not exist, find() will return null. You can just use a simple if to check:
if($restaurant = Restaurant::find($input["restaurant_id"]) {
// Do stuff to $restaurant here
}
You can also use
$restaurant = Restaurant::findOrFail($input["restaurant_id"]);
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:
From: https://laravel.com/docs/5.1/eloquent
Its very clear in laravel docs about your question, find(),first(),get(), all return null if the model not exist,
$model = Restaurant::find(111); // or
$model = Restaurant::where('id',111)->first();
if(!$model){ //if model not exist, it means the model variable is null
}

eloquent does not saves an object to database

The following code gives me an error "Whoops, looks like something went wrong." in laravel 4
$article = new Article;
$article->name = "second article";
$article->text = "second article desc";
print($article->save());
Here is my model
<?php
class Article extends Eloquent {
protected $table = 'article';
}
question: how enable debugger see inside browser to see what going wrong ?
In app/config/app.php set debug to true.
print outputs the value of a string, you probably want to use var_dump(), print_r() or Laravel's own dd() that dumps the passed variable and ends the script.
I had the similar issues where i created a table without migration. And used a Model. It was fetching the table but was not able to update. When ever i called $model->save() it throws me and error. Finally found that i forgot to add created_at and updated_at columns. I think laravel had made it mandatory for all tables.

Column name must be either a string or an array yii

i got some stuck when accessing a yii's web application. I have configured as the same as the owner's setting, but while i tried to access, i got an error "Column must be either a string or an array". How could i solve it? Thanks in advance..
When reporting error messages, it helps to have the precise error message. The actual error message is: "Column name must be either a string or an array". With an exact string you can search the framework files to find where it is mentioned.
Looks like some method somewhere is passing an invalid column name to createInCondition method of CDbCommandBuilder.
See line 722: https://github.com/yiisoft/yii/blob/1.1.13/framework/db/schema/CDbCommandBuilder.php
Looking at a couple instances where that method is called, I would guess that you have a database table without a primary key somewhere. That is one possible explanation for the problem. Other explanations will require a lot more details on your part.
Provide the stack trace that the error page provides you with when in debug mode along with your table schema.
This happens when you don't have a primary key in your table and you try to do an update. I got this problem because I had a composite primary key in my table. I was being handled well on all operations until I wanted to update a model.
Just add an int primary key, call it 'id' to your table with auto increment. It should do the trick.
Be sure to disable schema caching (if you're using that) before you test this. The change wont take effect until your schema cache expires.
Maybe you do not have primary key in your table. If you use the method $model->save() to save or use method $model->update() ($model is CActiveRecord instance), you will get this error.
Because the method update in CActiveRecord using Primary key to update (Read more here
)
Source Code: framework/db/ar/CActiveRecord.php#1115
if($this->_pk===null)
$this->_pk=$this->getPrimaryKey();
$this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
$this->_pk=$this->getPrimaryKey();
You can use method updateAll() instead of update() or updateByPk()
Take a look this link
http://www.yiiframework.com/forum/index.php/topic/3887-cdbexception-column-name-must-be-either-a-string-or-an-array/
It seems your table doesn't have a primary key or the primary key doesn't well restored which usually caused by corrupt back up file.
If you forgot add return value you will have error you showed. Simple example, your model with such method will return error on PK
...
public function relations()
{
}
...
Your have to add return value.
/**
* #return array
*/
public function relations()
{
return array();
}
If you are not using such methods you should delete them, or add 'default return values'. Otherwise it gives errors the same as it was primary key or other DB issues (because model read invalid data and didn't all things it should).

Update object instead of inserting with Doctrine using assignIdentifier()

I'm pretty new to Doctrine, but as I understand it, the assignIdentifier() method is supposed to tell Doctrine to update the relevant row into the database instead of inserting a new one.
I have an object that I'm building through a workflow, so the identifier has an id of null until I call $object->save(); which inserts it, and this does work.
If however I call $object->assignIdentifier($newobj->id); and then $object->save(); it does nothing - it does not insert a new row and does not update the old one.
If a certain condition is true, I want to pull a different record out of the DB and update that row instead of inserting the new one.
Am I understanding something wrong here?
Some code to illustrate:
if($this->object->payments > 0) {
$older_payment = Doctrine_Query::create()
->from('OldPaid p')
->where('p.dealid = ?', $this->object->transid)
->fetchOne()
;
$this->object->assignIdentifier($older_payment->id);
}
$this->object->save();
Like i got to know, save() will not update an existing record with autoincrement on ID.
I have the same problem using doctrine 1.2.
an idea i have use this one, the only workaroung i found:
$query = Doctrine_Query::create()->update('OldPaid');
$query->set($yourFieldname, '?', $yourValue);
$query->addwhere('p.dealid = ?', $this->object->transid);
$query->execute();
Thiw will function when a record is in the DN with the primaryKey dealid = $this->object->transid.
greeting m
Usually, if you retrieve a record, you can update it with the save() method. Doctrine recognizes this (since the PK doesn't change) and updates the record.
From the docs:
Updating objects is very easy, you
just call the Doctrine_Record::save()
method
Another way can be replace(), but I usually use just save() and does either the saving or the updating if the record already exists.
As far as I can read from the description of assignIdentifier() never used it myself) it will only work with retrieving an object by its ID, so updating something with this method will not work.

Doctrine findOneBy invalid field name where field does exist

I'm using Zend Framework with Doctrine. I'm creating an object, editing, then saving it. That works fine. However, when I later try to find that object based on one of the column values, Doctrine throws an error saying, "Message: Invalid field name to find by:". Notice there is no field name listed in the error message after the :.
My database table does have a column called status and the model base class does know about it. I'm using base classes and table classes in my setup.
Here is my code. The first section works fine and the record gets created in the database. Its the second line of the second section where the error gets thrown. I've tried different variations of the findBy calls, findBy('status', 'test1'), findByStatus('test1'), etc.
$credit = new Model_Credit();
$credit['buyer_id'] = 1;
$credit['status'] = 'test1';
$credit->save();
$creditTable = Doctrine_Core::getTable('Model_Buyer');
$credit = $creditTable->findOneByStatus('test1'); // dying here
$credit['status'] = 'test2';
$credit->save();
Never mind! I hate when you see the answer right after posting a big long question. In the second section I referred to a different model (Model_Buyer) instead of Model_Credit.

Categories