can use orWhere and Where functions with delete - php

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]]]
);

Related

Laravel count distinct value and get as associative array of key value pair

I have a field called language in my table submission. Here the different user has submitted their problem with different language such as java(56) 5 times, CPP(45) 7 times, and python(71) 10 times.
I want to have a query in laravel with eloquent such that it returns an array or with key-value pair as
$user_lang = ['56'=>5,'45'=>7,'71'=>10]
here 56,45,71 are the id of the languages
If you have prepared data like count of how many times, you can simply use pluck method. eg
$user_lang = Language::where(<condition>)->pluck('times', 'id');
It will return the array as you desired.
If you do not have prepared count, then count it using group by and simply use same pluck method .
$result = Submission::selectRaw('id', 'COUNT(DISTINCT id) AS times'))
->groupBy(id)
->get();
$user_lang = [];
$result->map($result, function($item){
$user_lang[$item->id] = $item->times;
});

My whereJsonContains not working (Laravel 5.8)

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();

How to get average of column values in laravel

Lets say I have this column
star
----
1
3
3
1
2
5
3
It has seven rows and there are integer values! I want to have it added and divided by the rows there are.
How do I do it in laravel. I can do it in plain php but I want to learn it in laravel.
Try this :
$avgStar = Model::avg('star');
" Model " will replace with your model name
If you want to do it with the query builder you can use aggregate methods like avg:
$avg_stars = DB::table('your_table')
->avg('star');
Laravel 5 docs about aggregates.
If you have more columns you can use the native function of the database manager using DB::raw
$products = DB::table('products')
->select('id','name',DB::raw('round(AVG(quantity),0) as quantity'))
->groupBy('id','name')
->get();
Table::Where('column', $case)->pluck('column')->avg()
Try this if you need to add multiple conditions:
$avgStar = YourModel::Where(
[
['column_1', '=', $case],
['column_2', '<>', 0]
.....
])->pluck('star')->avg();
// let's say the Model name is Review and Table name is reviews, you have a
'star' column on it
$value = Reviews::all();
$value->avg('star');
return view('page.name')->withValue($value);
// it will calculate an average of star column

Laravel 5.1 select field in with function

Can I select value from relationships with function "with" ?
So make something like this:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
Yes I know that I can put select in relation "user_detail" but can I select in with function?
You can select within with as you made the example given below:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
But it won't not work (as you commented in other answer) because you've only selected a single property but the foreign key is not available in your select statement. So, make sure that, you also select the related foreign key as well and then it'll work.
In your case, I believe that, you've to also select the user_id in your select for example:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select(
'user_id', // This is required if this key is the foreign key
'detail_1'
);
}])->get();
So, without the foreign key that makes the relation, Eloquent won't be able to load the related models and that's why you get null in your result as you mentioned in other comment.
Yes, you can use select() inside with(). Just pass an array of columns:
$query->select(['detail_1', 'detail_2']);
Alternatively, you can create another relation and add select() to it:
public function userDatails()
{
return $this->hasMany('App\UserDetail')->select(['detail_1', 'detail_2']);
}
$result = Staff::where('live_status',2)
->with('position')->with('department')->with('gender')
->with(['partner' => function($query){
$query->where('alive',0);
}]);

Use an array in Laravel update query

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]);

Categories