Am performing a find() in yii2 I understand that there can be andwhere but what of orWher
I have tried
$query = Tblpr::find()->where(['PRID'=>2])->andwhere(['new'=>1])->all();
How can i implement orWhere
Using Where OR
$query = Tblpr::find();
$query->andFilterWhere(['or',
['PRID',2],
['new',1]
])->all();
OR
$query = Tblpr::find()->select('*')
->orWhere(['PRID'=>2,'new'=>1])->all();
You can also use createCommand
$query = (new \yii\db\Query())
->select('*')
->from('Tblpr') // put your table name here
->where(['PRID'=>[2]])
->orWhere(['new'=>[1]]);
$command = $query->createCommand();
print_r ($command->sql);die;
The following should work for a query with ->where() and ->orWhere()
$query = Tblpr::find()
->where(['PRID' => 2])
->orWhere(['attribute' => 'value'])
->all();
Related
Am trying to perform this query
$command = $connection->createCommand("
SELECT
tbl_checklist.report_val AS item
FROM tbl_checks
LEFT JOIN tbl_checklist ON tbl_checklist.id = tbl_checks.check_id
WHERE truck_id = ".$value->id."
"
);
$results = $command->queryAll();
THe above works but i would like to perform the same using models
So i have tried
$results = TblChecks::find()
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
How do i add the SELECT tbl_checklist.report_val AS item in the Model flow
you should try like this
$results = TblChecks::find()->select(["tbl_checklist.report_val AS item","tbl_checks.*"])
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
Try this way, I hope it will solve your issue.
$results = TblChecks::find()
->select[tbl_checklist.report_val AS item]
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
You should use select() function:
$results = TblChecks::find()
->select('tbl_checklist.report_val AS item')
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
And add property $item in your model.
how I can to write this in Eloquent and I'm uisng laravel 4?
SELECT * FROM `applicant` WHERE `id`='17' OR `id`='19'
I am thinking like this
$findIDAUTH = Auth::User()->id;
$findHrsbu = HrSbu::where('staff_id', '=', $findIDAUTH)->get();
$results = Mapplication::MApplication();
foreach($findHrsbu as $HrSbu){
$results = $results->Where('sbu.id', '=', $HrSbu->sbu_id);
}
$results = $results->get();
if just
SELECT * FROM `applicant` WHERE `id`='17'
i'ts work but if
SELECT * FROM `applicant` WHERE `id`='17' OR `id`='19' or 'id'='20'
not working for me thanks
You should use whereIn with a subquery:
$results = Mapplication::whereIn('id', function ($query) {
$query->from((new HrSbu)->getTable())
->select('sbu_id')
->where('staff_id', auth()->id());
})->get();
Hi Please try with this code and let me know, here is an option by laravel as you used its a similar method....
$findIDAUTH = Auth::User()->id;
$findHrsbu = HrSbu::where('staff_id', '=', $findIDAUTH)->get();
$results = Mapplication::MApplication()->where(function($findHrsbu)->where(function($results) use ($findHrsbu) {
foreach($findHrsbu as $HrSbu){
$results->orWhere('sbu.id', '=', $HrSbu->sbu_id);
}
})->get();
Hy guys thanks for your answer..
Problem solved I'm using WhereIn
for ex : $results->whereIn('sbu.id', '=', array($dataArray));
I am new to Yii-2 framework. How can i achieve following query in Yii-2 framework using activeQuery and models.
SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)
Thanks
You can try this:
//SELECT * FROM users AS u WHERE u.user_id IN(1,5,8) AND (u.status = 1 OR u.verified = 1) OR (u.social_account = 1 AND u.enable_social = 1)
$model = arname()->find()
->andWhere(['user_id'=>[1,5,8]])
->andWhere(['or',
['status'=>1],
['verified'=>1]
])
->orWhere(['and',
['social_account'=>1],
['enable_social'=>1]
])
->all();
try this -
$query = (new \yii\db\Query())
->select('*')
->from('users u')
->where(['and',['u.user_id'=>[1,5,8]],['or','u.status=1','u.verified=1']])
->orWhere(['u.social_account'=>1,'u.enable_social'=>1]);
$command = $query->createCommand();
print_r ($command->sql);die;
more info
I assume that you have already knew about database configuration in Yii 2.0, which is basically the same as in Yii 1.0 version.
If you want to use activeQuery, you need to define a ‘USERS’ class first:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class USERS extends ActiveRecord {
public static function tableName()
{
return 'users';
}
}
?>
Then when you use it,you can write it as following:
<?
$usr_data = USERS::find()->
->where("user_id IN(1,5,8) AND (status = 1 OR verified = 1) OR (social_account = 1 AND enable_social = 1)")
->all();
?>
In my opinion, active query provides you a way to separate sql by sub-blocks. But it does not make any sense to apply it when you have such a complicated 'AND OR' WHERE condition..
U can also do it this way:
$data = model::find()
->andWhere('plz = :plz',[':plz' => 40])
->andWhere('plz = :plz',[':plz' => 40000])
->all();
User::find()
->select('u_id , u_unique_id, u_first_name, u_last_name, u_username, u_email, u_image,u_phone')
->andWhere("u_status != 2 AND u_id != 1 and u_role in (6,7)")
->andWhere(
['or',
['like', 'u_first_name', $searchVal],
['like', 'u_last_name', $searchVal],
['like', 'u_username', $searchVal],
['like', 'u_email', $searchVal]
]
)
->all();
With MongoDB:
$query->andWhere(['and',
['$eq', 'status', 1],
['$in', 'activity', [1, 2]],
]);
$query->orWhere(['$in', 'yourField', $yourArray]);
Tested. Similar with DBMS.
Use OR condition at first. For example:
(new \yii\db\Query())
->select(['id', 'client', 'ts', 'action'])
->from('log_client as log')
->orWhere(['action' => 'lock'])
->orWhere(['action' => 'rel'])
->andWhere(['in', 'client', $IDs])
->orderBy(['ts' => SORT_ASC])
->all();
It'll be like a "AND...(..OR..)"
where() function of ActiveQuery also accepts string as its first parameter that will be used in WHERE condition of the query. So easiest way would be to put those conditions in where()function.
Assuming you are using ActiveRecord model, you can do something like following in your model.
$this->find()
->where("user_id IN(1,5,8) AND (status = 1 OR verified = 1) OR (social_account = 1 AND enable_social = 1)")
->all();
Of course you should use prepared statements instead of hardcoding values inside query, but above code is just to give you an idea.
You can find more detail in documentation Here and Here
I'm very new to Laravel and don't quite understand the DB::table method in conjuction with an AND clause.
So I have this query at the moment:
$query = DB::select( DB::raw("SELECT * FROM tablethis WHERE id = '$result' AND type = 'like' ORDER BY 'created_at' ASC"));
It is working, but I'd like to use Laravel's Query Builder to produce something like:
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
But this seems to ignore the second where() completely. So, basically how do I make this work?
Just adding another ->where behind another ->where is the way to get another where statement
So your code should be fine.
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
There must be something wrong with a different part.
I do hope this isn't your full query.
If it is, you need a ->get() at the end.
For sure this code should work as expected.
I don't know how you check the query executed, but you can go to app/providers/EventServiceProvider.php (I assume you have L5) and in boot method add:
Event::listen(
'illuminate.query',
function ($sql, $bindings, $time) {
$sql = str_replace(array('%', '?'), array('%%', "'%s'"),
$sql);
$full_sql = vsprintf($sql, $bindings);
file_put_contents(storage_path() . DIRECTORY_SEPARATOR .
'logs' . DIRECTORY_SEPARATOR . 'sql_log.sql',
$full_sql . ";\n", FILE_APPEND);
}
);
to see exact SQL that was executed.
In addition (but it's just improvement) when using = operator, you can omit it, so you can use here:
$query = DB::table('tablethis')->where('id', $result)->where('type', 'like')->orderBy('created_at', 'desc');
I am using Eloquent ORM outside of Laravel-4 and I am building a custom Paginator.
First, I build a query using Fluent Query Builder. I want to get the number of result the query could return using count() and then I do a custom pagination using take(x) and skip(y). I need to do the count() before the take()->skip()->get() so I dont fall outside of the page range. The problem is that when I use the count() method on the query, it seems to remove any select I added previously.
I isolated the problem to this simple example:
$query = DB::table('companies')
->join('countries','companies.country_id','=','countries.id')
->select(
'companies.name as company_name',
'countries.name as country_name'
);
$nbPages = $query->count();
$results = $query->get();
//$results contains all fields of both tables 'companies' and 'countries'
If i invert the order of the count and get, it works fine:
$results = $query->get();
$nbPages = $query->count();
//$results contains only 'company_name' and 'country_name'
Question: is there a more elegant way the using something like this:
$tmp = clone $query;
$nbPages = $tmp->count();
$results = $query->get();
There is not, unfortunately. Open issue on github about the problem: https://github.com/laravel/framework/pull/3416