Making sql like query using yii2 model - php

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.

Related

Implementing an or where condition in yii2 find

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

yii2: Yii\db\Query in Model function

I am trying create a query in one of my model.php
The query is like
public function getBedCategory(){
$query = (new \yii\db\Query())
->select('room_category')
->from('room_charges')
->innerJoin('patient_detail',
'patient_detail.bed_type = room_charges.room_name')
->where(['room_charges.room_name'=> 'patient_detail.bed_type',
'patient_detail.id'=> $this->id]);
$command = $query->createCommand();
$rows = $command->queryOne();
//var_dump($command);exit;
return $rows;
}
When doing a var_dump for $command I am getting the sql query like this:
SELECT `room_category` FROM `room_charges`
INNER JOIN `patient_detail` ON patient_detail.bed_type = room_charges.room_name
WHERE (`room_charges`.`room_name`=:qp0) AND (`patient_detail`.`id`=:qp1)
and on var_dump of $rows I am getting boolean:false
What I am doing wrong here and why I am getting this :qp0 and :qp1
Thanks for any suggestion.
As Tahir correctly stated :qp0 and :qp1 are place holders for the parameters. These are replaced by static values on execution of the query. Your problem is that patient_detail.bed_type should not be parametized. Your code should therefore read:
...
->where(['room_charges.room_name = patient_detail.bed_type',
'patient_detail.id'=> $this->id]);
For more information on where(), you can view the API page.

How to print single value of entity without dumping the whole object?

I want to get one single value from entity.Can anyone help me here.
Here is my code.Please let me know what is missing here.
$query = $em->createQuery("SELECT e FROM AdminBundle:MailTemplates e WHERE e.keyword = '" .$keywordVal."'");
$query->execute();
$result = $query->getResult();
echo $result ->getId();
Here i want the 'id'.
This is noted in the documentation how you can do this.
So given you're code this will become:
$query = $em->createQuery("SELECT e.id FROM AdminBundle:MailTemplates e WHERE e.keyword = ?1");
$query->setParameter(1, $keywordVal);
$query->execute();
$result = $query->getResult(); // array of MailTemplates ids
Note: I also made use of setParameters instead of setting the value directly in the query.
In your controller:
$this->get('database_connection')->fetchColumn('select id from mail_templates where...');
That's much better for performance and much easier if you don't want to have a deal with query builder and other doctrine orm stuff.
Using the query builder you could do...
$queryBuilder = $em->createQueryBuilder('e');
$queryBuilder
->select('e.yourColumn')
// This will return just this column
// Alternatively you could omit any select to return the whole object
// that you could then use like $object->getYourColumn() if you so chose
->where($queryBuilder->expr()->eq('e.keyword', ':keyword'))
->setParameter('keyword', $keyword)
;
return $queryBuilder
->getQuery()
->getResult();
try this on loading Entities instead of creating own queries
Loading the entity with the Repository.
$rep = $this->getDoctrine()->getManager()->getRepository("Bundlename:Entity");
//find one by keyword -> single entity
$entity = $rep->findOneBy(array('keyword' => $keyword));
//find all by keyword - Array of entities
$result = $rep->findBy(array('keyword' => $keyword));

Eloquent ORM: count() remove the select(...)

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

Laravel: how to add where clause using query builder?

I have this query, made using Laravel query builder:
$rows = DB::table('elements')->where('type', 1);
That corresponds to: "SELECT * from elements WHERE type=1"
Now, in some cases I need to add a second Where to create a query like this:
SELECT * from elements WHERE type=1 AND lang='EN'
Using classic php I'd do something like:
$sql = 'SELECT * from elements WHERE type=1';
if($var==true) $sql .= " AND lang='EN'";
How can I do that using Laravel Query Builder?
Thank you.
You may try something like this
$query = DB::table('elements');
$query->where('some_field', 'some_value');
// Conditionally add another where
if($type) $query->where('type', 1);
// Conditionally add another where
if($lang) $query->where('lang', 'EN');
$rows = $query->get();
Also, check this answer.
$userId = Auth::id();
$data['user_list'] =DB::table('users')->
select('name')->
where('id','!=',$userId)->
where('is_admin','!=','1')->
get();
like that you use multiple where clause :)

Categories