How to do update query on laravel fluent using db::raw - laravel

This is related to one of my question earlier where:
Update table1 field with table2 field value in join laravel fluent
But since this is a different approach now, I will just ask another question:
How do you properly do an update using DB:raw?
I want to update the favorite_contents.type with the value of contents.type, but it doesn't do anything, the static setting of 1 to favorite_contents.expired is working.
This is my code which still doesn't update the type even when the DB::raw was used:
$table = 'favorite_contents';
$contents = DB::table($table)
->join('contents', function($join) use($table){
$join->on("$table.content_id", '=', 'contents.id');
})
->whereIn("$table.content_id",$ids)
->update(array(
"$table.expired" => 1
));
DB::raw("UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id");
This is the first code that doesn't update before I resorted to the above code that doesn't work as well:
$table = 'favorite_contents';
$contents = DB::table($table)
->join('contents', function($join) use($table){
$join->on("$table.content_id", '=', 'contents.id');
})
->whereIn("$table.content_id",$ids)
->update(array(
"$table.expired" => 1,
"$table.type" => "contents.type"
));
P.S:
This is working when done on an sql editor:
UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id

code raw updates like this:
...->update( array(
'column' => DB::raw( 'column * 2' )
) );

DB::statement("UPDATE favorite_contents, contents SET favorite_contents.type = contents.type where favorite_contents.content_id = contents.id");
Try DB::statement for raw queries that does not involve outputting something (select).

Will be work such similar, simple realization in Laravel 5.2 ,
Query Builder:
DB::table('stores')
->where('id', $request)
->update(['visibility' =>DB::raw($value)]);
This response is tested real site and working properly

Related

Laravel DB::select returns General error: 2031

Laravel DB::select returns
General error: 2031
It looks like quotes are not added to the statement and it tries to execute the statement like this:
$sql = 'SELECT id FROM users where email=email#email.com';
The code looks like this:
$sql = 'SELECT id FROM users where email=?';
$results = DB::select($sql, ['email' => $email]);
I thought this is handled automatically by PDO but do I need to add anything to the code above so the statement looks like?
$sql = 'SELECT id FROM users where email="email#email.com"';
I recommend you to read the select docs from Laravel Query Builder.
The Query Builder provides a complete API to make it easier and safer. Your query would look like:
$results = DB::table("users")->select("id")->where("email",$email);
EDIT
The problem is that you're trying to pass a named parameter, but inside the string you didn't named it.
As the doc example shows:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
Your query should look like:
$sql = 'SELECT id FROM users where email=:email';
$results = DB::select($sql, ['email' => $email]);
#mthrsj has correctly identified a better solution in your particular query.
Your underlying issue with the DB::select call is you're using non-named placeholders ? while passing it named data.
This should work:
$sql = 'SELECT id FROM users where email=?';
$results = DB::select($sql, [$email]);
as should this:
$sql = 'SELECT id FROM users where email=:email';
$results = DB::select($sql, ['email' => $email]);
If you have models setup, you can also call the DB using your User model:
$user = User::select('id')->where('email', $email)->get();
This uses Eloquent, which uses PDO.

Yii2 : Active Record add Not In condition

What is the active Record way of adding IN condition to an active Query
in yii 1.x you could use CDbCriteria like this
$cr = new CDbCriteria();
$cr->addNotInCondition('attribute', $array);
There seem to be no equivalent API call in yii2 active record implementation, how to do this via active record ?
Well all query operands seems now merged within in yii\db\QueryInterface::Where() per documentation
an In condition can now be added using something like
$query = MyModel::find()->where(['attribute'=>$array]);
for a not In condition it is slightly different format
$query = MyModel::find()->where(['not in','attribute',$array]);
$query = MyModel::findAll(['not in ','attribute',$array]);
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
For numbers:
$query = MyModel::find()->where('NOT IN('.implode(',', $array).')');
For strings
$deleteContracts = Contract::find()
->where([
'session_id' => $session_id,
'status' => Contract::STATUS_COMPLETED
])
->andWhere(['not in', 'contract_id', $contracts])
->all();
For me the only working solution was :
$query = MyModel::find()->where('`your-attribute` NOT IN(' . implode(',', $array) . ')')->all();

Elequent ORM ->where and ->save

I am new to Eloquent, and still getting my head round it, before i put the 'where' clause it it was working fine now i cant seem to get it to work.
$filesRelationship = self::user()->customer->submissions->where('period_timestamp', '=', Input::get('period_timestamp'))->customerfile();
$customerFile = new Customerfile(
array('path' => $savepath, 'document_id' => Input::get('document_id')
)
);
$customerFileResult = $filesRelationship->save($customerFile);
Depending on the relationships from your Models (you did not specify them), but this could work:
$filesRelationship = self::user()
->customer()
->submissions()
->where('period_timestamp', '=', Input::get('period_timestamp'))
->customerfile()
->first();

How to update column value in laravel

I have a page model. It has following columns in database table:
id
title
image
body
I want to update only "image" column value.
Here's my code:
public function delImage($path, $id) {
$page = Page::find($id);
$page->where('image', $path)->update(array('image' => 'asdasd'));
\File::delete($path);
}
it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
Try this method short and clean :
Page::where('id', $id)
->update(['image' => $path]);
An example from Laravel doc
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
DB::table('agents')
->where('id', $agentid)
->update(['status' => '0']);

Laravel 4: how to update multiple fields in an Eloquent model?

How can I update multiple fields in an Eloquent model? Let's say I got it like this:
$user = User::where("username", "=", "rok");
And then I have all these model parameters:
$new_user_data = array("email" => "rok#rok.com", "is_superuser" => 1, ...);
I can't just do:
$user->update($new_user_data);
What's the proper way? I hope not a foreach.
The following does work, however. Is this the way to go?
User::where("id", "=", $user->id)->update($new_user_data);
The problem with the last one (besides it being clunky) is that when using it from an object context, the updated fields are not visible in the $this variable.
The method you're looking for is fill():
$user = User::where ("username","rok"); // note that this shortcut is available if the comparison is =
$new_user_data = array(...);
$user->fill($new_user_data);
$user->save();
Actually, you could do $user->fill($new_user_data)->save(); but I find the separate statements a little easier to read and debug.
You are looking for this:
$user = User::where("username","rok")
->update(
array(
"email" => "rok#rok.com",
"is_superuser" => 1,
// ..
)
);
Refer : http://laravel.com/docs/4.2/eloquent#insert-update-delete
I should suggest to use shorter code, such as
$new_user_data=array('a'=>'n','b'=>'m');
$user=User::whereUsername('rok');//camelCase replaces "=" sign
$user->fill($new_user_data)->save();
Or even shorter
$new_user_data=array('a'=>'n','b'=>'m');
User::whereUsername('rok')->update($new_user_data);//camelCase replaces "=" sign
I believe the last statement is easier to debug and looks nicer.
Warning: If your table contains many users named 'rok' both mentioned statements will update all those registers at once. You should always update registers with the id field value.
Try this,
// took required data out of the request
$postData = request(
[
'firstName',
'lastName',
'address1',
'address2',
'address3',
'postcode',
'phone',
'imageURL',
]
);
// persisted it to the database
DB::table('users')
->where('id', auth()->user()->id)
);

Resources