How to fetch data from database with 3 parameters Laravel - mysql

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.

Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses

You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();

Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....

Related

mySQL query for building dynamically populated model

I have some code below which demonstrates a hard-coded example of what I would like to accomplish dynamically.
At a high level, I wish to do something like select * from view_data_$app_state and then get all of the data from that views table into my mustache templates dynamically.
The code I currently must use to group multiple rows of data for a specific column along with the views data is:
<?php
error_reporting(E_ALL);
class Example {
function __construct(){
try {
$this->db = new PDO('mysql:host=localhost;dbname=Example', 'root','drowssap');
}
catch (PDOException $e) {
print($e->getMessage());
die();
}
}
function __destruct(){
$this->db = null;
}
function string_to_array($links_string){
return explode(",", $links_string);
}
function get_view_data(){
$q = $this->db->prepare('select *, GROUP_CONCAT(`links`) as "links" from `view_data_global` ');
$q->execute();
$result = $q->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$Example = new Example();
$result = $Example->get_view_data();
$result[0]["links"] = $Example->string_to_array($result[0]["links"]);
echo json_encode($result);
This gives me the perfect object while
GROUP_CONCAT seems to be doing the trick this way, however I MUST know the column name that will contain multiple rows before writing the query. I am trying to figure out an approach for this and wish to make a custom query + code example that will transform cols with multiple rows of null null and not empty data into an array like above - but return the data.. again like the code above.
Below is an output of the actual data:
[{"id":"1","title":"This is the title test","links":["main","about","store"]}];
How can I replicate this process dynamically on each view table?
Thank you so much SO!
You can use PDOStatement::fetch to retrieve your results, with fetch_style set to PDO::FETCH_ASSOC (some other values will also provide the same information). In this case, the result set will be array indexed by column name. You can access this information with foreach (array_expression as $key => $value)
See the documentation for additional information.

Yii2: Conditional fill of Json data

I have a table ipd_charges like
id doctor_name charges_cash charges_cashless
1 1 300 600
2 2 200 400
and in my controller the code is like this which is working fine
public function actionCharges($id){
$model= \app\models\IpdCharges::findOne(['doctor'=>$id]);
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cash,
]);
}
Now what I want is to fill the data on condition and tried to modify the above code which is only returning the first condition in either case
public function actionCharges($id){
$model= \app\models\IpdCharges::findOne(['doctor'=>$id]);
$query = (new \yii\db\Query())
->select('tpa_name')
->from('patient_detail')
->innerJoin('daily_ward_entry',
'daily_ward_entry.general_regn_no = patient_detail.general_regn_no')
->where(['daily_ward_entry.id'=>$id]);
$command = $query->createCommand();
$rows = $command->queryAll();
if ($rows['tpa_name'] === NULL){
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cash,
]);
}else {
return \yii\helpers\Json::encode([
'visit_charges'=>$model->charges_cashless,
]);
}
}
Need a little clue what I am doing wrong here?
$model1= \app\models\Tpa::findOne(['tpa_name']);
You are specifying this condition wrong. You only provide column name without any condition.
Also you need to check $model for existence too.

Zend Framework - join query

I build a function
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'), array())
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId',
array())
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
And there are problems, that does'nt work! :D
Let's I explain you. Column 'bannedBy' from comments returns id of user, who give a ban. I need to join this with table users to load a login field. Where i have mistakes?
I assume the code works in the sense of not throwing an exception. If so, your code is OK, you just specifically tell Zend_Db not to select any columns.
public function getBannedByLogin($commentId)
{
$sql = $this->getDbAdapter()->select()
->from(array('comments' => 'comments'))
->join(array('users' => 'qengine_users'),
'comments.bannedBy = users.userId')
->where('commentId = ?', $commentId)
;
$row = $this->fetchRow($sql);
return $row['login'];
}
The last argument to from() and join() functions is an array of columns you wish to select. If you pass in an empty array, no columns are selected. No argument = select everything. You can, of course, specify only the columns you need too.

codeigniter sorting query results returned

I'm looking to sort the results of a query in the controller, "after" it is returned from the model, here is what im trying:
$query = $this->user->get_all_users();
foreach($query as $user){
// dynamically according to my projects' logic
// assigns a grade to each user
$user->grade = assign_a_grade_to_user()
}
what im looking to do is , the results in $query should be sorted according to the grade a student has , and then pass that sorted $query to my view to print
any suggestions or idea to get this ?
NOTE : no issues if we use another temporary variables or data structures like we can store the sorted results in some other variable too
This should do:
function cmp( $a, $b )
{
if( $a->grade== $b->grade){ return 0 ; }
return ($a->grade< $b->grade) ? -1 : 1;
}
$sortedArray=usort($query ,'cmp');
So your code should look like:
$query = $this->user->get_all_users();
foreach($query as $user){
// assigns a grade to each user
$user->grade = assign_a_grade_to_user()
}
$sortedArray=usort($query ,'cmp');
$data['users']=$query;
$this->load->view('home',$data);

Chaining orX in Doctrine2 query builder

I have to dynamically add OR expressions to the query builder returned by getListQueryBuilder, right after adding a where clause. I can't find any suitable way of doing this, i'm just started learning Doctrine.
How can i "chain" a given number of orX and add them to my builder?
public function getListQueryBuilder($ownerId)
{
$qb = $this->createQueryBuilder('t');
return $qb
->where($qb->expr()->eq('t.user', ':user'))
->setParameter('user', $ownerId);
}
$builder = getListQueryBuilder(4);
// $ORs is a dynamically builded array, here is just an example
$ORs = array();
$ORs[] = $builder->expr()->like("t.name", 'my name');
$ORs[] = $builder->expr()->like("t.description", 'desc');
// Adding ORs to the builder
$builder->andWhere($builder->expr()->orX(/* here */));
You can check this solution:
$orX = $builder->expr()->orX();
foreach($ORs as $or) {
$orX->add($or);
}
$builder->andWhere($orX);
I stumbled on the same problem and tried :
$builder->andWhere($builder->expr()->orX($ORs));
but it does not work since orX calls "return new Expr\Orx(func_get_args());" internally and you end up with something like array(array(or1, or2))
having looked at the API however i figured you can do this:
$builder->andWhere($builder->expr()->orX()->addMultiple($ORs));
OR do use $ORs table at all but issue:
$orx = $builder->expr()->orX();
$orx->add($builder->expr()->like("t.name", 'my name'));
$orx->add($builder->expr()->like("t.description", 'desc'));
$builder->andWhere($orx);