eloquent does not saves an object to database - php

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.

Related

Upgrading to Yii2, ORM not functional

I'm upgrading a big project form Yii1 to Yii2. I'm having some problems regarding to ORM.
I have several relation declared in the following fashion(basically a copy-paste from the guidebook):
class Order extends \yii\db\ActiveRecord {
/* other code */
public function getAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
Whenever I try to echo or w/e $order->affiliate->name; I get the following error:
yii\base\ErrorException: Trying to get property of non-object
I've got no experience with Yii1 what so ever. Something weird about this project is the database. All tables start with yii_tablename and id's are: id_tablename. Was that normal for Yii1 and could this be causing the issue above?
Edit: When I execute the function like so: $order->getAffilate() it returns an ActiveQuery WITHOUT the data from the affiliate.
When I execute the following:
$order->getBillingAddress()->one();
I get a weird error:
Getting unknown property: app\models\Order::billing
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
It's mean that when you call $order->affiliate yii2 will find in Affiliate table on id_affiliate field current Order affiliate_id value and selected one value.
Check that you have right field names and database have right data.
When you call $order->affiliate you will get Affiliate object. But if you call $order->getAffiliate() you will get ActiveQuery object.
I found a solution. One which I don't really like though, but it does the job. Was reading this thread: link.
Kartik V
The problem is clearly in uniqueness in naming your relation and your model attribute. In your User model, you have an attribute named role and you also have a relation getter named getRole.
So I changed the name of the getter like so:
public function getOrderAffiliate()
{
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}
And that fixed the issue. Never had this issue before and wonder why this happened though.

$model->save() adding 'where id = 1' condition

I'm trying to update a model, I load the model, take all the data from the POST and then save it, easy... But my record was never updating so went to the log and discovered that the update query is adding a weird condition. FYI, MD_ID is my primary key.
So, I load the model, the next line is the SQL produced by Yii:
$model = Ositems::model()->findByPk($id);
SELECT * FROM "MTODETALLADO_INV" "t" WHERE "t"."MD_ID"=249217
If echo the json_encode of the loaded model I get that dictionary in my browser:
echo json_encode($model->getAttributes());
{""MD_BODEGA":"01","MD_PRODUCTO":"0031253","MD_CANTIDAD":"1","MD_PRECIOTOTAL":"1466",,"MD_PORCENTAJEDESCUENTO":"0","MD_IDCABECERA":"97403","MD_ID":"249217","MD_OBSERVACION":null}
At this point everything looks right, now I take the values from post:
$model->attributes = $_POST;
And here if echo the values of the model I get the new values right, now here is the problem: I save the model and this is the SQL Yii runs (I replaced the :yp_ values to make it more readable)
$model->save();
UPDATE "MTODETALLADO_INV" SET
MD_BODEGA"='01'
MD_PRODUCTO"='0020514
MD_CANTIDAD"='10'
MD_PORCENTAJEDESCUENTO"='0
MD_IDCABECERA"=97403
MD_ID"=249218
MD_PRECIOTOTAL"='36210'
MD_OBSERVACION"=''
WHERE "MTODETALLADO_INV"."MD_ID"=1
And there is the problem! WHERE "MTODETALLADO_INV"."MD_ID"=1, Why would it make it 1 if all this time my model id has been 249218 ?
A few considerations:
My model only takes some columns that I need from the actual table, Yii sets the other columns as null and I omitted them in the previous code.
The table is in a foreign db, I use have a custom ActiveRecord which manages the CDbConnection to a database according to the user. (It's a webservice app)
I followed what the function save() did and could finally find the problem was when it tried to get the primary key. I had this method in my model:
public function primaryKey()
{
return array('MS_ID');
}
}
But it had to be:
public function primaryKey()
{
return 'MS_ID';
}
}
Somehow that was causing the problem.

Cannot insert to my new table

I have created a migration for ratings, and the table also working when i am entering phpmyadmin.
The problem is, i cannot figure out, how to write to the table?
I am running the code from "story" controller
I am using this:
$z = new Rating();
$z->story_id = 10;
$z->save();
print_r($z);
My "ratings.php" model:
<?php
class Rating extends Eloquent {
protected $table = 'ratings';
}
?>
Is there some place where i should notify laravel that new Rating() means my table "ratings"?
It doesn't seem like i have done the migration correctly, but i am completely new still, so hope someone can figure it out for me.
well instead of using the save() function for laravel you can use the insert() function
Rating->insert_get_id(array('story_id' => '10'));
or
$insert_id = Rating->insert_get_id(array('story_id' => '10'));
for insertion into table.This is much easy to use and I have used this in my whole project and so far I haven't face any problems.
Also if you have not created the model for rating table then go to the models folder under application folder and create a file name rating.php and inside the file write this:
class Rating extends Eloquent
{
public static $timestamps = false;
}
Also please note that table which you created in the phpmyadmin should have name of the form "ratings".
I hope this can be of some help.
I don't really understand what you're doing. Are you trying to write into the table from php? Is Rating a sort of database connection class? You need to create a mysqli object to connect to the database, write a query, and get a result. For best security use a prepared statement. Mysqli Documentation Sorry if I'm off-base about your question, I'm just not positive about what it is.

Twig and Symfony2 - Entity was not found

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;
}

Kohana ORM Update not working

I have discovered Kohana just 2 days ago and, after facing a few problems and managing to deal with them, I ran into a quite strange one.
When I try to update an entry in DB, instead of updating the entry ORM just inserts a new row.
Everything is similar to this example http://kohanaframework.org/3.0/guide/orm/examples/simple
My code (controller file):
class Controller_Admin extends Controller {
...
public function action_test($id)
{
$inquiry = ORM::factory('inquiry')->where('Id', '=', $id)->find(); // $inquiry = Model_Inquiry($id) doesn't work, too
$inquiry ->Name = 'Someone';
$inquiry ->save();
}
...
}
Model file:
class Model_Inquiry extends ORM
{
protected $_table_name = 'mytable';
}
Do you have any ideas why it's inserting a new entry instead of updating the old one? I read that it's because the ID is not correctly set, but I tried using a fixed value (->where('Id', '=', 5)) and it didn't work (it still inserted a new row).
Thanks in advance!
Your record isn't loaded in the first place. To check if it's loaded, do:
if ($inquiry->loaded()){...
Also, you can check what query has been run by doing:
echo $inquiry->last_query();
So you can manually check what exactly is being returned to ORM.
The main problem here is that you're using save() instead of being more strict and using create() / update(). If you used update(), ORM would throw an exception complaining about the record not being loaded.
Save is basically a proxy to these methods, relying on the loaded state.
(I assume that you're using Kohana 3.1 since 3.0 ORM doesn't have separate update / create methods at all)

Categories