How to select items by providing where clause in pivot - sql

This is my code looks like right now :
$result = Category::with(array(
"getProducts",
"getProducts.getBrand",
"getProducts.getImages",
"getProducts.getDetail",
"getProducts.getTax",
"getProducts.getDiscount",
"getProducts.getAttributes" => function($query) use($_temp){
if($_temp != null){
$query->where_in('attributes.id',$_temp);
}
},
"getSlideshow",
"getSlideshow.getItems",
"getAttributeListing",
"getAttributeListing.getAttributes",
"getAttributeListing.getAttributes.productSpecific"
))
->where('id','=', $category_id)
->first();
Yet, It only filters the getProducts.getAttributes items not the 'getProducts' itself. Is there a way that I can get the Products by attributes?
Note: I am using Laravel 3

Related

Can Laravel automatically switch between column = ? and column IS NULL depending on value?

When building a complex SQL query for Laravel, using ? as placeholders for parameters is great. However when the value is null, the SQL syntax needs to be changed from = ? to IS NULL. Plus, since the number of parameters is one less, I need to pass a different array.
To get it to work, I have written it like this, but there must be a better way:
if ($cohortId === null) {
// sql should be: column IS NULL
$sqlCohortString = "IS NULL";
$params = [
Carbon::today()->subDays(90),
// no cohort id here
];
} else {
// sql should be: column = ?
$sqlCohortString = "= ?";
$params = [
Carbon::today()->subDays(90),
$cohortId
];
}
$query = "SELECT items.`name`,
snapshots.`value`,
snapshots.`taken_at`,
FROM snapshots
INNER JOIN (
SELECT MAX(id) AS id, item_id
FROM snapshots
WHERE `taken_at` > ?
AND snapshots.`cohort_id` $sqlCohortString
GROUP BY item_id
) latest
ON latest.`id` = snapshots.`id`
INNER JOIN items
ON items.`id` = snapshots.`item_id`
ORDER by media_items.`slug` ASC
";
$chartData = DB::select($query, $params);
My question is: does Laravel have a way to detect null values and replace ? more intelligently?
PS: The SQL is for a chart, so I need the single highest snapshot value for each item.
You can use ->when to create a conditional where clause:
$data = DB::table('table')
->when($cohortId === null, function ($query) {
return $query->whereNull('cohort_id');
}, function ($query) use ($cohortId) {
// the "use" keyword provides access to "outer" variables
return $query->where('cohort_id', '=', $cohortId);
})
->where('taken_at', '>', $someDate)
->toSql();

Laravel QueryBuilder condition

In Laravel, I want to build a query like following.
There is a status column, value should be 0 or 1.
And there is another column, device_ids with array.
Now,in query, I want to apply different logic on device_ids, when status is 0 and status is 1.
Can someone suggest me best possible way.
$builder->where('status','0')->whereJsonDoesntContain('device_ids', $imei_id->id)
$builder->where('status','1')->whereJsonContains('device_ids', $imei_id->id)
How can I combine both ?
$all_applications = $builder->where('status', $model->status)
->when($status, function ($query) {
Log::error("One");
return $query->whereJsonContains('device_ids', 107); },
function($query) {
Log::error("Zero"); return $query
->whereJsonDoesntContain('device_ids', 107); });
If I use $model->status , it gives me error like , "Undefined variable: model"
You have to use when.
$result = YourModel::where('status', $status)
->when($status, function ($query) {
return $query->whereJsonContains('device_ids', $imei_id->id);
}, function ($query) {
return $query->whereJsonDoesntContain('device_ids', $imei_id->id);
});

Doctrine QueryBuilder multiple distinct

I would like to restrict results with DISTINCT on two columns using doctrine ORM
My function is like this :
public function findFdvLinkedToPdv($pointVenteCodes){
$queryBuilder =
$this->createQueryBuilder('r')
->leftJoin('r.forceVente', 'forceVente')
->leftJoin('r.pointVente', 'pointVente')
->leftJoin('r.signature', 'signature')
->leftJoin('signature.affaire', 'affaire')
->andWhere('pointVente.code IN (:pointvente_codes)')
->orderBy('forceVente.matricule', 'ASC')
->addOrderBy('pointVente.code', 'ASC')
->addOrderBy('affaire.code', 'ASC')
->addOrderBy('r.type', 'ASC')
->setParameters(array('pointvente_codes' => $pointVenteCodes,))
->select(array(
'forceVente.matricule AS forcevente_matricule',
'pointVente.code AS pointvente_code',
'affaire.code AS affaire_code',
'r.id AS id',
'r.profil AS profil',
'r.type AS type',
'forceVente.nom AS nom',
'forceVente.prenom AS prenom',
'forceVente.email AS email',
'r.deletedAt AS deletedAt'));
return $queryBuilder->getQuery()->getArrayResult();
}
For each forcevente.matricule and each pointVente.code , I have from 2 to 6 rows. I would like to get one row for each couple forcevente.matricule/pointVente.code I have to do a distinct on both columns, but when I try :
->select(array(
'DISTINCT forceVente.matricule AS forcevente_matricule',
'DISTINCT pointVente.code AS pointvente_code',
'affaire.code AS affaire_code', etc ...
I have a doctrine error ...
[EDIT]
I do this in PHP after executing the request to filter the results...
//BEGIN PATCH
$i=0;
$linkedForceVentes2 = array();
foreach ($linkedForceVentes as $item) {
if (!isset($linkedForceVentes2[$item['pointvente_code']][$item['forcevente_matricule']])){
$linkedForceVentes2[$item['pointvente_code']][$item['forcevente_matricule']] = $item;
}else{
unset($linkedForceVentes[$i]);
}
$i++;
}
//END PATCH
I finaly resolved it with a groupBy :
->groupBy('forcevente_matricule', 'pointvente_code', 'type' , 'affaire_code');
Just after the select statement.

Conditions in JOINed tables shows error CakePHP

I have two tables employee_personals where all the personal record of the employee is stored and telephone_bills where the telephone bills paid to a particular employee is stored for each month. Now in my employeePersonalsController.php I have a function called api_show_employees() which is similar to below :
function api_show_employees() {
//$this->autoRender = false;
//Configure::write("debug",0);
$office_id = '';
$cond = '';
if(isset($_GET['office_id']) && trim($_GET['office_id']) != '') {
$office_id = $_GET['office_id'];
$cond['EmployeePersonal.office_id'] = $office_id;
}
if(isset($_GET['telephoneBillTo']) && isset($_GET['telephoneBillFrom']) ) {
if($_GET['telephoneBillTo'] != '' && $_GET['telephoneBillFrom'] != '') {
$cond['TelephoneBill.bill_from'] = $_GET['telephoneBillFrom'];
$cond['TelephoneBill.bill_to'] = $_GET['telephoneBillTo'];
}
}
$order = 'EmployeePersonal.name';
// $employee = $this->EmployeePersonal->find('all');
$employee = $this->EmployeePersonal->find('all',array('order' => $order,'conditions'=>$cond));
//return json_encode($employee);
}
This functions basically finds all the employees who paid bills in the given period. But I am getting an error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TelephoneBill.bill_from' in 'where clause'
Models : EmployeePersonal.php:
var $hasMany = array(
'TelephoneBill' => array(
'className' => 'TelephoneBill',
)
);
TelephoneBill.php
public $name = 'TelephoneBill';
var $hasMany = array('EmployeePersonal');
NB: If I skip the bill_from and bill_to conditions, I am getting the results , with TelephoneBill array !
TLDR: use Joins instead.
Details/Notes:
1) it looks like you're using recursive. Don't do that. Use Containable instead.
2) You can't limit the parent model based on conditions against data from a contained/recursive-included table - instead, use Joins.
2b) Or, you could query from the other direction, and query your TelephoneBill with conditions, then contain the EmployeePersonal.

Yii CDbCommand create query

I can't create the following query using Yii:
SELECT recipientId as broadcasterId, SUM(quantity) as quantity FROM `creditlog`
WHERE websiteId=3 AND timeAdded>='2013-01-17'
AND timeAdded<='2013-02-17'
AND recipientId IN (10000024, 10000026, 1000028) GROUP BY `recipientId`
I tried:
$command = Yii::app()->db->createCommand();
$command->select('recipientId as broadcasterId, SUM(quantity) as quantity');
$command->from('creditlog');
$command->where('websiteId=:websiteId AND timeAdded>=:dateStart AND timeAdded<=:dateEnd AND recipientId IN (:recipients)',array(':websiteId' => $websiteId, ':dateStart' => $dateStart, ':dateEnd' => $dateEnd, ':recipients' => $broadcasterIds));
$command->group('recipientId');
also the andWhere() function which is in the docs seems to be missing.
The issue is that IN condition but I can't find a way to rewrite it.
Since you don't have access to andWhere, which would make life much simpler, you have to express the parameters with where like this:
$command->where(array(
array('and',
'websiteId=:websiteId',
array('and',
'timeAdded>=:dateStart',
array('and',
// ...
), $parameters);
This is done so that you can at some point use the proper array('in', 'recipientId', $values) syntax to produce the IN(...) SQL.
However, this is ugly and difficult to manage. As long as all the conditions are simply joined together with AND you can construct the data structure programmatically from a saner data representation like this (in effect this is a workaround for the missing andWhere):
$conditions = array(
'websiteId=:websiteId',
'timeAdded>=:dateStart',
'timeAdded<=:dateEnd',
array('in', 'recipientId', $broadcasterIds),
);
$where = null;
foreach ($conditions as $condition) {
if (!$where) {
$where = $condition;
}
else {
$where = array('and', $where, $condition);
}
}
$command->where($where, $parameters);
For more information on why this way of expressing things has to be used you can refer to the documentation for CDbCommand::where.