I want to know the problem related to this code, first I use a table without primary key when I run the following code to an update, I did not have any answer:
Upload::where('nameimgs', '=', $imgsended)
->update(array('nameimgs' => $ imgname));
but the problem is solved when I replace the code by :
DB::table('uploads')
->where('nameimgs', '=', $ imgsended)
->update(array('nameimgs' => $ imgname));
nevertheless with the deleting method, i did not have any problem, to share knowledge with laravalists I want to know if the problem is related to version Laravel4.2 or Laravel ORM eloquent for the update method require the primary key "id" as like as the save method.
Is the exact code you have in your project? If so, you have spaces in the field names, and you are missing a comma in the first where.
Upload :: where ('nameimgs '' = ', $ imgsended) -> update (array (' nameimgs' => $ imgname));
DB :: table ('uploads') -> where ('nameimgs', '=', $ imgsended) -> update (array ('nameimgs' => $ imgname) );
It should look like this:
Upload::where('nameimgs', $imgsended)
->update([
'nameimgs' => $imgname
]);
DB::table('uploads')
->where('nameimgs', $imgsended)
->update([
'nameimgs' => $imgname
]);
Try my code see if that fixes anything. If that doesnt work, can we see you Upload model?
Related
I once wrote probably same question last time and I'm back..
Laravel Eloquent firstOrCreate doesn't work properly
On the last question, I found that fillable property filters update field manifest. So, if you want to update a table based on fieldA and fieldB, then your code might be..
$modelOrRelation->updateOrCreate(
['fieldA' => 'a', 'fieldB' => 'b'], ['otherfields' => 'update value']
);
and you MUST specify those fields on fillable property. $fillable = ['fieldA', 'fieldB', ...]
This is what I know about firstOrCreate and updateOrCreate.
At this time, following code generate many same rows. It looks like, the first parameter ['candle_date_time_kst'] do nothing..
// candleRelation is hasMany relation..
$candleRelation = $market->candles($period);
$created = $created->add($candleRelation->updateOrCreate(
[
'candle_date_time_kst' => $time,
],
$item
));
This creates many same candle_date_time_kst value rows. At this time, fillable property already filled target fields.
What else do I miss?
Is updateOrCreate should not trust? I didn't think so.. There are something I miss... any insight?
#220114 update
So, I do my homework..
Using DB::getQueryLog(), I get this query..
It looks like, updateOrCreate() remembers the last update value. Then if I reuse same eloquent relation object for another updateOrCreate(), method use last update parameter again. It makes and clause, so return record is none..
So, I use newQuery() method for initialize query bindings.
$created->add($candleRelation->newQuery()->updateOrCreate(
[
'candle_date_time_kst' => $time
],
$item
));
#220114
Unfortunately, retest reveals newQuery() actually not helping..
I tried $relation->newModelInstance() and getting same bindings.
What I trying to do is getting same parent binding without anything else. .. anyone knows?
Based on binding, when I get relation model I can get clean binding also. So I just do below..
$created->add($market->candles($period)->updateOrCreate(
[
'candle_date_time_kst' => $item['candle_date_time_kst']
],
$item
));
Only change is $candleRelation to $market->candles($period).
On each attempt, new relation instance produce so binding problem won't even exists.
.... I'm mad.
you need to supply an array in the format
[ column => value, ... ] not [ value ]
I had a similar problem a time ago. And the UpdateOrInsert method solved it.
Unfortunately, this method is Query Builder, not eloquent. But to achieve this result that was the only really working solution to me.
The issue for only happened when I tried to use more than 1 column on where clause, like in your example.
I have an Eloquent model on which I would like to increment a single attribute. So far I've been using the following line of code to achieve this:
Thread::where('id', $threadId)->increment('like_count');
This however has the unwanted side-effect of updating the updated_at timestamp. I've found the following way of updating a record without altering the timestamp:
$thread = Thread::where('id', $threadId)->first();
$thread->timestamps = false;
$thread->like_count++;
$thread->save();
But that suddenly looks a lot less concise. Therefore, I would like to know of there's a way to use the increment method without updating timestamps.
If you do not need timestamps at all, you can disable it once for all for that particular model using :
public $timestamps = false; inside your model. This will add additional step that whenever you want the timestamps to be updated, you need to assign them value manually like $object->created_at = Carbon::now()
Secondly, if you want those disabled for particular query, then as you mentioned in your question is one way.
Another way is using query builder. Now timestamps is the functionality associated with Eloquent. However, if you update using simple query builder, it does not update timestamps on its own.
So you can do :
DB::table('threads')
->where('id', $threadId)
->update([ 'votes' => DB::raw('votes + 1') ]);
However, I will personally prefer using Eloquent way of doing this if given a choice.
Update
You can now pass additional parameter to increment function to specify what other columns you would like to update.
So this will become :
$thread = Thread::find($threadId);
$thread->increment('votes', 1, [
'updated_at' => $thread->updated_at
]);
old thread but with laravel 7 and php7.4 you can do
Thread::where('id', $threadId)
->where(fn($q) => $q->getModel()->timestamps = false)
->increment('like_count');
older versions of php:
Thread::where('id', $threadId)
->where(function($q) {$q->getModel()->timestamps = false;})
->increment('like_count');
You could encapsulate the whole process into one method of the model.
Is there a way to update only 1 row in Laravel 5? I want to set the value of selected to true from only 1 row, ordered by id:
Ill tried:
DB::table('user_tabs')->where('user_id', '=', $user_id)->orderBy('id', 'desc')->take(1)->update(array('selected' => true));
And:
DB::table('user_tabs')->where('user_id', '=', $user_id)->orderBy('id', 'desc')->first()->update(array('selected' => true));
but it is not working. Any ideas?
Try this:
DB::table('user_tabs')->where('user_id', $user_id)->update(['selected' => true]);
You were trying to update the record after selecting it, which confused the Query Builder.
Also, have a look at Eloquent models. They make database interactions a little nicer.
I'm importing a bunch of csv entries in my database with Laravel 4.
I can't really point at one column that has to be unique, it's a combination of 5 columns that makes it unique. However: how does one define this in Laravel?
Option 1: schema builder
You can use the $table->unique('email') method, but that only seems to allow one column, not a combination of columns.
Option 2: Validation
Less preferable, but I could validate the model before inserting it. However, again, using 'unique:[table]' validation rules, it will return an error when just one of the column values isn't unique, not a combination of them.
Can anyone tell me how I should go about this?
I'm sure I'm missing something, but I could use a push in the right direction :-)
Thanks,
Dieter
You can combine:
$table->unique( array('email','name') );
And pretty much everything in Laravel will accept arrays to do whatever you need to with 'more than one'.
Use Schema Builder's unique() method to define your data model, as Antonio mentioned.
Additionally, if you want to use validation on your model, consider my custom Validator rule for multiple UNIQUE indexes: https://github.com/felixkiss/uniquewith-validator
You can also do this;
$table->unique(["column1", "column2"], 'uq_columns');
Which means that you will have a unique column combination of all the columns i.e. column1 and column2
I know this question is for Laravel 4, but I just came across this on searches and found a solution for Laravel >= 5.3
Here it is:
Of course, the migration may look something like
$table->unique( array('email','name') );
Then to validate this, you do not need to use custom rules, just advanced rules:
'email' => Rule::unique('users')->where(function ($query) use ($request) {
return $query->where('name', $request->name);
}),
Of course, you may want to validate name before of this. The name should be required so that you may finish with something like this:
'name' => 'required|max:255',
'email' => Rule::unique('users')->where(function ($query) use ($request) {
return $query->where('name', $request->name);
}),
I hope it helps.
You can try this
$table->string("name");
$table->string("email")->unique("name")
I am trying to set up a custom entity, following along alan storms article about it, but with this simple install script, it tells me that Can't create table: extended_categories_text. When i look in the database, i can actually see the following tables:
extended_categories
extended_categories_datetime
extended_categories_decimal
extended_categories_int
My install script is deadsimple and looks like this:
<?php
$installer = $this;
$installer->addEntityType('csvengine_extendedcategories',Array(
'entity_model' =>'csvengine/extendedcategories',
'attribute_model' =>'',
'table' =>'csvengine/extendedcategories',
'increment_model' =>'eav/entity_increment_numeric',
'increment_per_store' =>'0'
));
$installer->createEntityTables(
$this->getTable('csvengine/extendedcategories')
);
How can i get my install script working? Is this a known magento bug?
After my previous post, I got a little farther in the same tutorial, but I still ran into issues. Finally, I was lead to these two posts which allowed me to complete the tutorial:
http://www.magentocommerce.com/bug-tracking/issue/?issue=12336
http://www.magentocommerce.com/bug-tracking/issue/?issue=12126
The last one points out an error in the version of Magento I was using.
Mage_Eav_Model_Entity_Setup , Line 1341:
->addForeignKey($this->getFkName($eavTableName, 'entity_id', 'eav/entity', 'entity_id'),
'entity_id', $this->getTable('eav/entity'), 'entity_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
Should be:
->addForeignKey($this->getFkName($eavTableName, 'entity_id', 'eav/entity', 'entity_id'),
'entity_id', $baseTableName, 'entity_id',
Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
I had the same issue with 1.7.0.0.
I found that the problem was in the transaction (line 1359) of the createEntityTables() method, but I don't know why...
So I just copied the whole createEntityTables() method to my install script ( I don't wanna mess with the core!), moved the foreach loop (line 1361) out of the transaction and everything worked fine!
As to why beginTransaction() could be throwing an exception, I have no idea!
I encountered the same problem. In my situation I realized that the error occurring when trying to create the database table was: BLOB/TEXT column 'value' used in key specification without a key length
To force Magento to render SQL statements that my database could accept, I had to modify the app/code/core/Mage/Eav/Model/Entity/Setup.php file at approximately line 1337 (inside the createEntityTables method). Replacing the following lines:
->addIndex($this->getIdxName($eavTableName, array('attribute_id', 'value')),
array('attribute_id', 'value'))
->addIndex($this->getIdxName($eavTableName, array('entity_type_id', 'value')),
array('entity_type_id', 'value'))
With this:
->addIndex($this->getIdxName($eavTableName, array('attribute_id', 'value')),
array('attribute_id', $type == 'text' ? array('name' => 'value', 'size' => 255) : 'value'))
->addIndex($this->getIdxName($eavTableName, array('entity_type_id', 'value')),
array('entity_type_id', $type == 'text' ? array('name' => 'value', 'size' => 255) : 'value'))
I used this ticket to solve the above problem: BLOB/TEXT column 'value' used in key specification without a key length
If this doesn't solve your problem, I would suggest going into the lib/Varien/Db/Adapter/Pdo/Mysql.php file inside the createTable method and adding the following code just before the return statement:
echo "<pre>SQL:\n$sql\n\n</pre>";
This way you can see what SQL your database is having issues with so you can try it in an SQL client (ie. phpMyAdmin) that will give you a more descriptive explanation of what's going wrong.