I would like to push an array in Where Clause of Laravel Update Query.
Here is the update query.
DB::table('users')->where('id', 1)->update(array('votes' => 1));
Is it possible to use the query like below ??
$array_of_ids;
DB::table('users')->where($array_of_ids)->update(array('votes' => 1));
Thanks
Simply use whereIn:
$array_of_ids;
DB::table('users')->whereIn('id', $array_of_ids)->update(array('votes' => 1));
Please read the documentation carefully. In this case, all kinds of where statements are documented here: Query Builder - Selects
Try this query:
DB::table('users')->whereIn('id', $array_of_ids)->update(['votes' => 1]);
Using Model:
User::whereIn('id', $array_of_ids)->update(['votes' => 1]);
using the query builder: The query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
Related
I have problem with my laravel query.
Now I use query like this:
$courses = Course::whereJsonContains('schedule->day', 1)->get();
It doesn't work.
I'm using postgreSql 9.6 and my database and raw query look like this
http://sqlfiddle.com/#!17/88fd2/1/0
I want to select class where have schedule in day = 1
If you define the column as schedule->day, MySQL assumes that this is an array of integers. In your case it's an array of objects, so you have to target the parent array and add the property name you are looking for in the second argument.
Like so:
$courses = Course::whereJsonContains('schedule', ['day' => 1])->get();
I solved with
$courses = Course::whereJsonContains('schedule', [['day' => '1']])->get();
I solved with
$products=ProductShop::active()
->whereJsonContains('tag', [['value' => "tampa"]])->get();
If you're querying the value уоu don't need to use whereJsonContains, simply use a regular where query such as:
$courses = Course::where('schedule->day', 1)->get();`
If you want to check if day exists in Json, use whereJsonLength such as:
$courses = Course::whereJsonLength('schedule->day', '>', 0)->get();
Yii2 framework why i cant use this?
$rows = new Query;
$rows->createCommand()
->delete('friends')
->Where(['userid' => 1 ,'userid' => 2])
->orWhere(['userid' => 2 ,'userid' => 1])
->execute();
In the where() and or orWhere() function you are using an hash format (['key'=> 'value'])
Hash Format Hash format is best used to specify multiple
AND-concatenated sub-conditions each being a simple equality
assertion. It is written as an array whose keys are column names and
values the corresponding values that the columns should be.
Lookin to you code This is equivalent to
where userid = 1 and userid = 2
look a this for na useful guide http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
second but most important .. in Yii2 you have delete() and deleteAll()
delete() Deletes the table row corresponding to this active record.
deleteAll() Deletes rows in the table using the provided conditions.
this is working code
$rows->createCommand()->delete('friends',['userid' =>[1,2], 'friendid' =>[1,2])->execute();
Try this
Friends::deleteAll(['and',
[ 'userid'=>3],
['in', 'userid', [1,5,7]]]
);
I was wondering how can I build a condition based query in Laravel using eloquent?
I've found how to do it with a raw query but that that's not what I want also the answer to this question isn't that dynamic at least not as dynamic as I want it to be.
What I try to achieve is to create a dynamic WHERE query based on certain conditions, for example if the field is filled or not.
If I use the following code,
$matchThese = [
'role' => 'user',
'place' => \Input::get('location')
];
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
The query will fail if I don't send a location as POST value. I don't want it to fail I want it to skip to the next WHERE clause in the query. So basically if there's no place given don't search for it.
Build up the query and include the ->where() clause depending on whether or not you have the location in your input:
$query = User::where('role', 'user');
$query = \Input::has('location') ? $query->where('location', \Input::get('location')) : $query;
$availableUsers = $query->take($count)->orderByRaw('RAND()')->get();
Just build the array with an if condition:
$matchThese = [
'role' => 'user',
];
if(\Input::has('location')){
$matchThese['place'] = \Input::get('location');
}
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
$query = DB::table('table_name');
if($something == "something"){
$query->where('something', 'something');
}
$some_variable= $query->where('published', 1)->get();
You can use something like this.
I'm trying to upgrade my project L5.1 -> L5.2. In upgrade guide there's one thing which isn't clear for me:
The lists method on the Collection, query builder and Eloquent query
builder objects has been renamed to pluck. The method signature
remains the same.
That's ok, rename refactoting from lists() to pluck() isn't a problem. But what with useful pluck() method which was in L5.0 and L5.1?
From the 5.0 documentation:
Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
What is the alternative for old pluck() method in L5.2?
UPDATE:
Example:
var_dump(DB::table('users')->where('id', 1)->pluck('id'));
L5.1:
// int(1)
L5.2:
// array(1) { [0]=> int(1) }
The current alternative for pluck() is value().
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
laravel pluck returns an array
if your query is:
$name = DB::table('users')->where('name', 'John')->pluck('name');
then the array is like this (key is the index of the item. auto incremented value):
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
but if you do like this:
$name = DB::table('users')->where('name', 'John')->pluck('name','id');
then the key is actual index in the database.
key||value
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
you can set any value as key.
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3] and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
In the original example, why not use the select() method in your database query?
$name = DB::table('users')->where('name', 'John')->select("id");
This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...
Larvel 5.3: Specifying a Select Clause
How would I use query builder in Laravel to generate the following SQL statement:
SELECT costType, sum(amountCost) AS amountCost
FROM `itemcosts`
WHERE itemid=2
GROUP BY costType
I have tried several things, but I can't get the sum() column to work with a rename.
My latest code:
$query = \DB::table('itemcosts');
$query->select(array('itemcosts.costType'));
$query->sum('itemcosts.amountCost');
$query->where('itemcosts.itemid', $id);
$query->groupBy('itemcosts.costType');
return $query->get();
Using groupBy and aggregate function (sum / count etc) doesn't make sense.
Query Builder's aggregates return single result, always.
That said, you want raw select for this:
return \DB::table('itemcosts')
->selectRaw('costType, sum(amountCost) as sum')
->where('itemid', $id)
->groupBy('costType')
->lists('sum', 'costType');
Using lists instead of get is more appropriate here, it will return array like this:
[
'costType1' => 'sumForCostType1',
'costType2' => 'sumForCostType2',
...
]
With get you would have:
[
stdObject => {
$costType => 'type1',
$sum => 'value1'
},
...
]