cakephp hasmany query on same class - mysql

i am using this binding
$this->Company->bindModel( array(
'hasMany' => array(
'CompanyContactPerson'=>array('conditions' => array('Company.name Like'=>'%'.$a.'%'),),
),
'belongsTo' => array(
'Status',
'User'
)
));
$this->paginate = array(
'limit' =>20,
'conditions'=>$conditions,
'order' =>array('Company.id'=> 'desc') ,
);
$all_companies = $this->paginate('Company');
It give this query as a result.
SELECT `Company`.`id`, `Company`.`user_id`, `Company`.`name`, `Company`.`status_id`, `Company`.`email`, `Company`.`modified`, `Company`.`created`, `Status`.`id`, `Status`.`name`, `User`.`id`, `User`.`roll`, `User`.`username`, `User`.`email`, `User`.`password`, `User`.`first_name`, `User`.`last_name`, `User`.`gender`, `User`.`address`, `User`.`city`, `User`.`state`, `User`.`country`, `User`.`modified`, `User`.`created`
FROM `companyinfo`.`companies` AS `Company`
LEFT JOIN `companyinfo`.`statuses` AS `Status` ON (`Company`.`status_id` = `Status`.`id`)
LEFT JOIN `companyinfo`.`users` AS `User` ON (`Company`.`user_id` = `User`.`id`)
WHERE 1 = 1 ORDER BY `Company`.`id` desc LIMIT 20
it make seperate query for CompanyContactPerson model. so as a result i got all result from Company table. I need only those rows from company table where CompanyContactPerson conditions is satisfied . how i achieved this

put this in your Company model so it can have a relationship. :)
public $hasMany = array(
'CompanyContactPerson' => array(
'className' => 'CompanyContactPerson',
'foreignKey' => 'ForeignKeyinCompanyContactPerson',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => '',
'dependent' => true
)
));
or put this to your CompanyContactPerson Model
public $belongsTo = array(
'Company' => array(
'className' => 'Company',
'foreignKey' => 'ForeignKeyofCompanyContactPersonTABLE',
'conditions' => '',
'fields' => '',
'order' => ''
)
);

Use limit in Query
'limit' => 2, //int
So only two rows will be returned.
Your code should be like
'CompanyContactPerson'=>array('conditions' =>
array('Company.name Like'=>'%'.$a.'%'),
'limit' => 2
),

Related

How to get WooCommerce products from database based on multiple attributes

I want to get related products based on some criteria on product attributes like, the same sku, ean and gtin codes. But my query doesn't return any results. I tried different ways to query the database but all fail. Here is my query.
$sku = $product->get_sku();
$ean = $product->get_attribute( 'EAN' );
$gtin = $product->get_attribute( 'GTIN' );
$query = new WP_Query( array(
'post_type' => array('product'),
'posts_per_page' => 20,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_sku',
'value' => $sku,
'compare' => '='
)
),
'tax_query' => array(
array(
'taxonomy' => 'pa_ean',
'field' => 'value',
'terms' => $ean,
'operator' => '=',
),
array(
'taxonomy' => 'pa_gtin',
'field' => 'value',
'terms' => $gtin,
'operator' => '=',
)
)
) );
By the way, if a product has ean code than it doesn't have a gtin and vice versa. It always has a sku which is unique to it self. But I have it added as a check to check if query at least returns value.
I can't find good documentary on this topic and hope someone here can help.

Fetch random row from group by query (mysql) in Cakephp

I have a table 'activities' and the columns are grouped by three of its attributes. Now I want to fetch Activity ID that is randomly selected from all the set of groups. The query is as follows:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
));
These are the things I tried and none of them worked.
1. Create a self join which should have random records
$this->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'Activity',
'order' => 'rand()',
'foreignKey' => 'id',
'fields' => 'Random.id'
)
)
));
This failed because the rand() order is appended in the end which simply randomizes all fetched activities.
Added a join option
'joins' => array(
array(
'table' => 'activities',
'alias' => 'Random',
'type' => 'LEFT',
'conditions' => array(
'Activity.id = Random.id'
),
'fields' => 'Random.id',
'order' => 'rand()'
)
This also didn't work as order value is not parsed by Cake
Tried to add condition
'Activity.id >= floor(rand() * (max(Activity.id) - min(Activity.id)) - min(Activity.id))'
Gave a mysql error
Please help me out
Assuming that your query is working:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
'order' => 'rand()',
'limit' => '1' // if you only want one random activity ID
));
Ok finally figured it out. We need to hack the way cake php works. In place of table name, I wrote a query to fetch randomly ordered records. Also notice the join type is 'right'. Left join wont produce randomly sorted list
$activities = $this->find('all', array('conditions' => $cond,
'page' => $page,
'limit' => $limit,
'fields' => array('count(*) as count, Random.id as id, max(Activity.modified) as Modified'),
'group' => $group,
'order' => 'Modified desc',
'joins' => array(
array(
'table' => '(select * from activities order by rand())',
'alias' => 'Random',
'type' => 'RIGHT',
'conditions' => array(
'Activity.id = Random.id'
),
)
)
));

Association of models(JOIN) not working in cakephp, shows empty results

I am purely new to cakephp and currently working on a project that is built in version 1.3. Basically I am trying to display the city names of the providers which are inserted in the database.
I have two models : gal_store.php and gal_location.php. In the gal_store model, the stores names are saved with their corresponding city ids in city field in gal_stores table. The table gal_locations contains all the cities and their names.
So I tried to JOIN the two tables as below :
var $hasOne = array(
'GalLocation' => array(
'className' => 'GalLocation',
'foreignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
function getList($limit = 50,$whether_list = false){
$recursive = -1;
$conditions = array("GalStore.city"=> "GalLocation.id");
//$conditions = "";
$order = array("GalStore.address");
if($whether_list == true){
return $this->find("list",array("DISTINCT GalStore.city","recursive"=>$recursive,"limit"=>$limit,"order"=>$order,"conditions" => $conditions));
}else{
return $this->find("all",array("DISTINCT GalStore.city","recursive"=>$recursive,"limit"=>$limit,"order"=>$order,"conditions" => $conditions));
}
}
But in the ctp file when I do a var_dump($gal_locations); it always shows empty ! What is the reason ?
If the gal_locations has one to one relationship with gal_stores, use below code:
var $hasOne = array(
'GalLocation' => array(
'className' => 'GalLocation',
'foreignKey' => 'city',//if the city field contains the id of gal_locations table
'conditions' => '',
'fields' => '',
'order' => ''
),
);
If the gal_locations has one to many relationship with gal_stores, use below code:
var $belongsTo = array(
'GalLocation' => array(
'className' => 'GalLocation',
'foreignKey' => 'city',//if the city field contains the id of gal_locations table
'conditions' => '',
'fields' => '',
'order' => ''
),
);

join two model from one model in cakephp

i want to fetch record form 2 model (Booking and Message), both model don't have any relation.
i try a lot but its not working
i used that code ( http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables )
$options['joins'] = array(
array('table' => 'books_tags',
'alias' => 'BooksTag',
'type' => 'inner',
'conditions' => array(
'Book.id = BooksTag.book_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'inner',
'conditions' => array(
'BooksTag.tag_id = Tag.id'
)
)
);
$options['conditions'] = array(
'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options);
Try this:
BookModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'book_id'
)
);
TagModel:
public $hasMany = array(
'BooksTag' => array(
'foreignKey' => 'tag_id'
)
);
BooksController:
$this->Book->Behaviors->load('Containable');
$this->Book->find('all', array(
'contain' => array(
'BooksTag' => array(
'Tag',
),
),
));
I prefer to do this on many queries. First find the required tag:
$this->loadModel('Tag');
$tag = $this->Tag->find('first', array('conditions' => array('Tag.tag' => 'Novel')));
$tag_id = $tag['Tag']['id'];
Then find book_ids:
$this->loadModel('BookTag');
$book_ids = $this->BookTag->find('list', array('conditions' => 'BookTag.tag_id' => $tag_id, 'fields' => 'book_id, book_id'));
Then find books:
$this->Book->find('all', array('conditions' => array('Book.id' => $book_ids)));
It is a long code but runs fast and is easy to understand. Another way is to use sub-queries but they are ugly and may slow down your application

Cakephp model with conditions

Is it possible to make relation in cakephp model with some specific conditions:
eg:
var $belongsTo = array(
'Parent' => array(
'className' => 'Category',
'foreignKey' => 'parent_id',
'dependent' => true
)
);
I want the above relation on where field parent_id is not 0. Please give some overview on How to do that?
You can put conditions in the relations just like you do with finds.
var $belongsTo = array(
'Parent' => array(
'className' => 'Category',
'foreignKey' => 'parent_id',
'dependent' => true,
'conditions' => array(
...
)
)
);