ManyToMany left join query builder - sql

I have entity A with ManyToMany doctrine relation wite entity B
I want to get data of the entity A using query builder in this way
$data = array(
0 => array(
'entity_A_field_1' => 'entity_A_field_1_value',
'entity_A_field_2' => 'entity_A_field_2_value',
'entity_A_field_3' => 'entity_A_field_3_value',
'entity_B' => array(
0 => array(
'entity_B_field_1' => 'entity_B_field_1_value',
'entity_B_field_2' => 'entity_B_field_2_value',
'entity_B_field_3' => 'entity_B_field_3_value',
),
2 => array(
'entity_B_field_1' => 'entity_B_field_1_value',
'entity_B_field_2' => 'entity_B_field_2_value',
'entity_B_field_3' => 'entity_B_field_3_value',
),
),
),
1 => array(
'entity_A_field_1' => 'entity_A_field_1_value',
'entity_A_field_2' => 'entity_A_field_2_value',
'entity_A_field_3' => 'entity_A_field_3_value',
'entity_B' => null
),
);
her is my entities: entity A is product
class Product
{
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="products",cascade={"persist", "remove"})
*
* #ORM\JoinTable(
* name="store_product_category"
* )
*/
private $categories;
Entity B is category
class Category
{
/**
* #ORM\ManyToMany(targetEntity="Product", mappedBy="categories")
*/
private $products;
I want to get all my products with their categories using query builder and without conditions (if they have| null if they don't). i need to get them all.
$data = array(
0 => array(
'product_id' => 'product_id_value',
'product_name' => 'product_name_value',
'product_reference' => 'product_reference_value',
'categories' => array(
0 => array(
'category_id' => 'category_id_value',
'category_name' => 'category_name_value',
'category_token' => 'category_token_value',
),
2 => array(
'category_id' => 'category_id_value',
'category_name' => 'category_name_value',
'category_token' => 'category_token_value',
),
),
),
1 => array(
'product_id' => 'product_id_value',
'product_name' => 'product_name_value',
'product_reference' => 'product_reference_value',
'category' => null
),
);

Related

How to sub query a select into another select and put inside a variable with laravel?

I want to make a select that solves the fact that I have to perform two validations one for each table, what i'm doing now is validating the $table1 and validating the $table2 ,i just want to validate $table2
$table1 = DB::table('name_table1')
->where('invoice_id','{$table2}.id')
->get();
$table2 = DB::table('name_table2')
->select('name','invoices','{$table} as itens_of_invoice')
->get();
dd($table);
And return me something like;
Array (
[0] => Object(
'name' => 'value_name',
'invoices' => 'value_invoices',
'item_of_invoice' =>
Array(
[0] => Array(
'name_item' => 'value_name',
'price' => 'value_price'
)
)
)
[1] => Object(
'name' => 'value_name',
'invoices' => 'value_invoices',
'item_of_invoice' =>
Array(
[0] => Array(
'name_item' => 'value_name',
'price' => 'value_price'
)
)
)
[2] => Object(
'name' => 'value_name',
'invoices' => 'value_invoices',
'item_of_invoice' =>
Array(
[0] => Array(
'name_item' => 'value_name',
'price' => 'value_price'
)
)
)
)
I don't find any solution if someone ever did this please help me

Yii cactivedataprovider count duplicates record and all record count

$criteria = new CDbCriteria;
$criteria->group = 't.blahah_id';
$result = new CActiveDataProvider('SocialnetworkSpams', array(
'criteria' => $criteria,
));
echo "<pre>";
print_r($result->getData());
Array
(
[0] => SocialnetworkSpams Object
(
[total] =>
[_new:CActiveRecord:private] =>
[_attributes:CActiveRecord:private] => Array
(
[id] => 1
[created_date] => 2015-12-04 03:50:47
[feedtype] => 1
[feedback] =>
[spam_status] => 1
[approveby_id] => 1
[blahah_id] => 1
[bunit_id] => 3
[spamby_id] => 1
)
[_related:CActiveRecord:private] => Array
(
)
[_c:CActiveRecord:private] =>
[_pk:CActiveRecord:private] => 1
[_alias:CActiveRecord:private] => t
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
[1] => SocialnetworkSpams Object
(
[total] =>
[_new:CActiveRecord:private] =>
[_attributes:CActiveRecord:private] => Array
(
[id] => 4
[created_date] => 2015-12-04 04:24:07
[feedtype] => 5
[feedback] => a
[spam_status] => 0
[approveby_id] =>
[blahah_id] => 2
[bunit_id] => 3
[spamby_id] => 1
)
[_related:CActiveRecord:private] => Array
(
)
[_c:CActiveRecord:private] =>
[_pk:CActiveRecord:private] => 4
[_alias:CActiveRecord:private] => t
[_errors:CModel:private] => Array
(
)
[_validators:CModel:private] =>
[_scenario:CModel:private] => update
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
)
I want duplicate record get using blahah id you can check bellow image:
Thanks
I have been resolved this issue.
$criteria = new CDbCriteria;
$criteria->select = '*, count(*) as total';
$criteria->group = 't.blahah_id';
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
View Page :
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'spam-user-grid',
'itemsCssClass' => 'table table-striped table-bordered table-hover',
'dataProvider' => $model->search(),
'template' => "{items}{pager}",
'pager' => array(
'header' => '',
),
'columns' => array(
array(
'header' => 'Blahah',
'type' => 'raw',
'value' => 'ucfirst($data->ratingprofile->name)',
//'filter' => CHtml::textField('User[name]'),
),
array(
'header' => 'Total',
'type' => 'raw',
'value' => '$data->total',
),
),
)
));

not work scopes in Yii

Why my scopes not work?
$criteria = new \CDbCriteria();
$criteria->addCondition('user_id = :user_id');
$criteria->scopes = array(
'applicant' => array(
'scopes' => array('deletedStatus'),
'params' => array(':deletedStatus' => 0)
),
'filePair' => array(
'with' => array(
'category' => array(
'with' => array(
'parent' => array(
'order' => 'parent.order'
)
),
'scopes' => array('enabled')
),
'file' => array(
'scopes' => array('enabled'),
'order' => 'file.order'
)
)
)
);
$criteria->params = array(':user_id' => \Yii::app()->userApp->id);
/** #var \ApplicantDocument[] $models */
$models = \ApplicantDocument::model()->findAll($criteria);
public function scopes()
{
$t = $this->getTableAlias(false, false);
return array(
'deletedStatus' => array(
'condition' => $t.'.is_deleted = :deletedStatus'
),
'applicant' => array(
'condition' => $t.'.role = :role',
'params' => array(':role' => self::APPLICATION_STATUS_APPLICANT)
),
'guarant' => array(
'condition' => $t.'.role = :role',
'params' => array(':role' => self::APPLICATION_STATUS_GUARANTOR)
),
'company' => array(
'condition' => $t.'.role = :role',
'params' => array(':role' => self::APPLICATION_STATUS_COMPANY)
),
'trust' => array(
'condition' => $t.'.role = :role',
'params' => array(':role' => self::APPLICATION_STATUS_TRUST)
),
);
}
This scope does not work, aplicants with is_deleted selected from db
'applicant' => array(
'scopes' => array('deletedStatus'),
'params' => array(':deletedStatus' => 0)
),
Thanks for help!
Scopes not working, coz it call in ApplicantDocument, not in applicant. So i am try it solution and it help me.
$criteria->with = array('applicant');
$criteria->together = true;
$criteria->condition = "applicant.is_deleted = 0";

CakePHP many conditions to one field

This code:
$conditions = array(
'fields' => array(
'User.id'
),
'conditions' => array(
'AND' => array(
'UsersProblem.problem_id' => 38,
'UsersProblem.problem_id' => 34,
),
),
'recursive' => -1
);
$conditions['joins'][] = array(
'table' => 'users_problems',
'alias' => 'UsersProblem',
'type' => 'INNER',
'conditions' => array(
'User.id = UsersProblem.user_id',
));
Is transforming to this SQL query:
SELECT `User`.`id`
FROM `lawyers`.`users`
AS `User`
INNER JOIN `lawyers`.`users_problems`
AS `UsersProblem`
ON (`User`.`id` = `UsersProblem`.`user_id`)
WHERE `UsersProblem`.`problem_id` = 34
Where is AND UsersProblem.problem_id = 38"?
How to create correct find condition to get users with some list of problems? Which are linked as many to many relationship.
Using $this->Problem->find is not possible, beause I need to use 2 joins: users_problems and users_practices. And use for them AND condition, like this:
'AND' => array(
'UsersProblem.problem_id' => 38,
'UsersProblem.problem_id' => 34,
'UsersPractices.practice_id' => 1,
'UsersPractices.practice_id' => 2,
),
You're overwriting 'UsersProblem.problem_id'. Just think about it like the array it is. CakePHP is just using the PHP array structure to do these finds, and that means it follows array rules. But to get around that in cakephp, you're supposed to use a two dimensional array
Like this:
'AND' => array(
array('UsersProblem.problem_id' => 38),
array('UsersProblem.problem_id' => 34)
),
Instead of this:
'AND' => array(
'UsersProblem.problem_id' => 38,
'UsersProblem.problem_id' => 34
),
That way, instead of trying to set the key 'UsersProblem.problem_id' twice, you're making an array that looks like
0 -> array('UsersProblem.problem_id' => 38)
1 -> array('UsersProblem.problem_id' => 34)
And that will work, it's a workaround the CakePHP guys built into the system for this kind of situation.
I think you need to use OR instead of AND:
$conditions = array(
'fields' => array(
'User.id'
),
'conditions' => array(
'OR' => array(
array('UsersProblem.problem_id' => 38),
array('UsersProblem.problem_id' => 34),
),
),
'recursive' => -1
);
You can also roll this up as follows:
$conditions = array(
'fields' => array(
'User.id'
),
'conditions' => array(
'OR' => array(
'UsersProblem.problem_id' => array(34, 38)
),
'recursive' => -1
);
Change your conditions array as shown below:
$options = array(
'fields' => array('User.id'),
'conditions' => array('UsersProblem.problem_id' => array(38,34)),
'recursive' => -1
);
$options['joins'] = array(
array(
'table' => 'users_practices',
'alias' => 'UsersPractices',
'type' => 'INNER',
'conditions' => array(
/CONDITION OF JOIN/
),
array(
'table' => 'users_problems',
'alias' => 'UsersProblem',
'type' => 'INNER',
'conditions' => array(
'User.id = UsersProblem.user_id',
)
);
From User Model:
$this->find('list',$options);
Do not use AND/ OR because they are not optimized for above case.
For reference:
MYSQL OR vs IN performance
and
CakePHP right way to do this (get value from setting's table)
**Try the code for join tables in cakephp.......**
$options = array('joins' => array(
array(
'table' => 'modelname1',
'alias' => 'modelName1',
'type' => 'LEFT',
'foreignKey' => false,
'conditions' => array('modelname1.id = modelname2.mid')
)
),
'fields' => array('modelName1.field1', 'modelName1.field2', 'modelName2.field1', 'modelName2.field2'),
'conditions' => array('modelname.id' => 1, 'modelname2.field1' => ''),
'limit' => 10, 'page' => 1);
$this->modelName2->find($options);

Populating CGridView one to many relation

In my project one of the model named types having multiple relation to other models the criteria with part is giving below its like
$criteria->with = array(
'category',
'subCategory',
'accountsSupplierPriceDetails' => array(
'with' => 'serviceLevel'
)
);
the relationship goes like
types - category - relation(1-1)
types - subcategory - relation(1-1)
types - accountsSupplierPriceDetails - relation(1-1)
accountsSupplierPriceDetails - serviceLevel - relation(1-n)
my problem is how to display the names from each table in a grid. the result of (1-n) should be displayed in a dropdownbox. when i try to access the data from column it shows the error Trying to get property of non-object ($data->accountsSupplierPriceDetails->serviceLevel ->name). can anyone please help me.
Thanks in advance.
in my view i create a cgridview with 5 rows in which one row data is populated using dropdownlist.
<div style="width:700px; height:auto;">
<?php
$widget = $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'response-grid',
'dataProvider' => $pickdataset->pickCategorylistingForMain(),
'cssFile' => Yii::app()->baseUrl . '/media/css/gridview.css',
'summaryText' => '',
'ajaxUpdate' => 'response-grid',
'enablePagination' => true,
'pager' => array(
'class' => 'LinkPager',
'cssFile' => false,
'header' => false,
'firstPageLabel' => 'First',
'prevPageLabel' => 'Previous',
'nextPageLabel' => 'Next',
'lastPageLabel' => 'Last',
),
'columns' => array(
array(
'name' => 'id',
'header' => '#',
'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'type' => 'raw',
'name' => 'categoryExt',
'header' => 'Category',
),
array(
'type' => 'raw',
'header' => 'Sub Category',
'value' => '$data->subCategory->name',
),
array(
'type' => 'raw',
'name' => 'locationExt',
'header' => 'Location',
),
array(
'type' => 'raw',
'header' => 'Name',
'value' => 'CHtml::dropDownList($data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,"",popDropBox($data->masterCategoryServiceLevels), array("class" => "listbox"), array("empty" => "Select a Location"))',
),
array(
'type' => 'raw',
'header' => 'Pick',
'value' => 'CHtml::image(Yii::app()->baseUrl . "/media/images/edit_icon.png",$data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,array("title" => "Select this Combination"))',
),
),));
function popDropBox($data)
{
$list = array();
foreach ($data as $row)
{
$list[$row->serviceLevel->id] = $row->serviceLevel->name;
}
return $list;
}
?>
</div>
the relation in model is:
'masterCategoryServiceLevels' => array(self::HAS_MANY, 'MasterCategoryServiceLevel', 'category_template_id'),
'corporate' => array(self::BELONGS_TO, 'AccountsCorporate', 'corporate_id'),
'category' => array(self::BELONGS_TO, 'MasterCategory', 'category_id'),
'subCategory' => array(self::BELONGS_TO, 'MasterCategory', 'sub_category_id'),
'location' => array(self::BELONGS_TO, 'MasterLocation', 'location_id'),
the row is
array(
'type' => 'raw',
'header' => 'Name',
'value' => 'CHtml::dropDownList($data->corporate_id."-".$data->category_id."-".$data->sub_category_id."-".$data->location_id,"",popDropBox($data->masterCategoryServiceLevels), array("class" => "listbox"), array("empty" => "Select a Location"))',
),
and i use a function to create dropdown data is
function popDropBox($data)
{
$list = array();
foreach ($data as $row)
{
$list[$row->serviceLevel->id] = $row->serviceLevel->name;
}
return $list;
}
please comment if you have any doubt. i am free to share... have a nice day SO friends... wishes and prayers.