Good day.
I am relatively new to yii2.
What am I trying is this sort of SQL query:
SELECT * FROM table WHERE a=1 AND (b=1 OR b=2)
How do I write such query via yii2 query builder?
You need to use orWhere() , andWhere() and where() functions.
the "or" and "and" words are the type of union it made with all the previous where conditions
so, this query:
Table::find()->where('b=1')->orWhere('b=2')->andWhere('a=1')->all();
Make something like this:
select * from Table where (((b=1) or b=2) and a=1)
The all() function tell yii2 to select al records its founds
Note: this code dont work, its just and example.
This can be done like this:
$model = User::find()
->where('a = :a', [':a' => 1])
->andWhere('b = :b1 or b = :b2', [':b1' => 1, ':b2'=> 2])
->all();
Related
This SQL:
SELECT COUNT(*) AS total_see_all_video
from users u
WHERE 7 = (SELECT COUNT(*) FROM lecciones_users lu WHERE lu.uuid = u.uuid)
I tried this code but did not work:
$data = LeccionesUsers::select(
DB::raw('COUNT(*) AS total_ase_vis_videos'),
DB::raw('where 7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
)
->join('users', 'lecciones_users.uuid', '=', 'users.uuid')
->get();
Your issue is that you are not correctly forming your query. You can do ->toSql(); instead of ->get(); and you would see the final SQL (would definitely not be the same as the one you wrote first).
So, you should have this to have the same SQL:
$total_see_all_video = LeccionesUsers::whereRaw('7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
->count();
Please, try my query (and also run ->toSql() to see if you have a correct SQL).
I would still recommend to use relationships and it is very weird to do 7 = query.
You can use
DB::query()->fromSub('Raw sql query here..')
and then can perform actions on this.For the reference you can use the documentation fromSub
You can also look into this convert this where break this query to parts to be used accordingly. You can use this section for the reference purpose:
Laravel-Raw-Expressions
Hope this will help you with the result.
Is there a way or can someone translate this to code igniter query builder.
SELECT result.id, result.name, result.added
FROM (SELECT tbl.id, tbl.name, tbl.date_added
FROM table tbl
GROUP BY tbl.id) result
GROUP BY result.date_added
I already have my research(link below) but can't find anything like this(query above).
https://www.codeigniter.com/userguide3/database/query_builder.html
https://arjunphp.com/how-to-write-subqueries-in-codeigniter-active-record/
And yes, this can be done using Stored Procedure but I have another reason why I need to implement this as query builder.
try this one.
// Sub Query
$this->db->select('result.id, result.name, result.added')->from('table tbl');
$subQuery = $this->db->get_compiled_select();
// Main Query
$this->db->select('result.id, result.name, result.added')
->from('table tbl')
->where("id IN ($subQuery)", NULL, FALSE)
->get()
->result();
I have to execute this query
select count(id) as numberofcompanies, sum(offered_value) as total_offered_value from campaign_comapany
where ( campaign_id in (select id from campaing where user_id = current_user ) or campaing_company.sp_user_id = current_user)
and campaign_company.status = '3'
And I wrote the query like this in yii2-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->andFilterWhere(['or',['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])],['=','campaign_company.sp_user_id',Yii::$app->user->id]])
->andWhere(['=','status','3'])
->one();
But it gives me error with unknow column campaign_company.user_id
but working if I just use where like following-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])])
->andWhere(['=','status','3'])
->one();
What should I do to get the result mentioned sql query, I don't want to hit database server two time, thanks in advance
Use join:
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->innerJoin('campaign','`campaign`.`id` = `campaign_company`.`campaign_id`')
->where([
['=','campaign.user_id',Yii::$app->user->id])],
['=','campaign.campaign_company.sp_user_id',Yii::$app->user->id],
['=','campaign_company.status','3']
]
->one();
As is it is difficult to follow your logic. To simplify your code and your query, add the first condition as plain sql. Also since the second condition is required, you can swap the positions as follows:
$query
->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['status' => '3'])
->andWhere(['
campaign_id in (select id from campaign where user_id = :current_user )
or campaign_company.sp_user_id = :current_user1',
[':current_user' => Yii::$app->user->id, ':current_user1' => Yii::$app->user->id]])
->one();
I have following query,
SELECT * FROM `users` WHERE approved='1'
and users.id NOT IN (SELECT donations.user_id FROM donations where month='1'
and year='2016');
I have followed Laravel Query Builder WHERE NOT IN
and converted my query like this,
$users = DB::table('users')->where('approved','=',1)->whereNotIn('id', function($q){
$q->select('user_id')->from('donations')->where('month','=','$month')->where('year','=','$year');
})->get();
But its not working, can anybody help me out where i am making mistake.
how can I convert it into Laravel query builder format?
Thanks.
You shouldn't put your $month and $year variables in quotes.
Replace
->where('month','=','$month')->where('year','=','$year')
with
->where('month','=',$month)->where('year','=',$year)
Good morning,
I've been trying for quite a lot of time to translate this query(which returns an array of stdClass) into query builder so I could get objects back as Eloquent models.
This is how the query looks like untranslated:
$anketa = DB::select( DB::raw("SELECT *
FROM v_anketa a
WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)
Order by redni_broj limit 1"
), array( 'lv_id_user' => $id_user,
));
I have tried this, but it gives a syntax error near the inner from in the subquery:
$anketa = V_anketa::selectRaw("WHERE not exists (select 1 from user_poeni where anketa_id=a.id and user_id = :lv_id_user)", array('lv_id_user' => $id_user,)
)->orderBy('redni_broj')->take(1)->first();
The problem is this exists and a subquery in it. I couldn't find anything regarding this special case.
Assume each table has an appropriate Eloquent model.
V_anketa is a view. The db is postgresql.
As far as the query goes I believe this should work:
$anketa = V_anketa::whereNotExists(function ($query) use ($id_user) {
$query->select(DB::raw(1))
->from('user_poeni')
->where('anketa.id', '=', 'a.id')
->where('user_id', '=', $id_user);
})
->orderBy('redni_broj')
->first();
but I'm not clear on what do you mean by "assuming every table has an Eloquent model" and "V_anketa" is a view...
Assuming the SQL query is correct, this should work:
$anketa = DB::select(sprintf('SELECT * FROM v_anketa a WHERE NOT EXISTS (SELECT 1 FROM user_poeni WHERE anketa_id = a.id AND user_id = %s) ORDER BY redni_broj LIMIT 1', $id_user));
If you want to get back an Builder instance you need to specify the table:
$anketa = DB::table('')->select('');
If you however, want to get an Eloquent Model instance, for example to use relations, you need to use Eloquent.