Use OR conditions on associated model in CakePHP 3 - cakephp-3.0

I have 3 models, the base model is Jobs and Customers, Contacts are the models associated with jobs. Here is the association.
$this->belongsTo('Customers', [
'className' => 'Customers',
'foreignKey' => 'customer_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Contacts', [
'className' => 'Contacts',
'foreignKey' => 'contact_id',
'joinType' => 'INNER'
]);
I want to search a text in all the 3 tables and return the job records which are having the search text at least any one of the tables... I want to achieve this using CakePHP's ORM...
This is the raw SQL you may want as the reference,
$searchText = 'Bikash';
$JobQ->query("SELECT *
FROM Jobs
LEFT JOIN Customer ON Jobs.CustomerID=Customers.CustomerID
LEFT JOIN Contacts ON Jobs.ContactID=Contacts.ContactID
WHERE (
Job.JobName LIKE '%" . $searchText . "%' or
Customer.Name LIKE '%" . $searchText . "%' or
Contact.FirstName LIKE '%" . $searchText . "%' or
Contact.Surname LIKE '%" . $searchText . "%');

If you are following cake conventions should be simply:
$jobs = $this->Jobs->find()
->contain(['Customers', 'Contacts'])
->where([
'OR' => [
'Jobs.JobName LIKE' => '%" . $searchText . "%',
'Customers.Name LIKE' => '%" . $searchText . "%',
'Contacts.FirstName LIKE' => '%" . $searchText . "%',
'Contacts.Surname LIKE' => '%" . $searchText . "%'
]
]);
or using query expressions
$jobs = $this->Jobs->find()
->contain(['Customers', 'Contacts'])
->where(function ($exp, $query) {
return $exp->or_([
$exp->like('Jobs.JobName', "%$searchText%"),
$exp->like('Customers.Name, "%$searchText%"),
$exp->like('Contacts.FirstName, "%$searchText%"),
$exp->like('Contacts.Surname', "%$searchText%")'
]);
});

Related

How use between cakephp

it does not return any error but neither any row but if there are fields but it does not collect them, which may be failing the query
$tarea = $this->Signs
->find('all', [
'conditions'=> array(
'date_inicio BETWEEN "' .
$horaInicio->format('Y-m-d H:i:s') .
'" and "' .
$horaFin->format('Y-m-d H:i:s') .
'"'
)
])
->where([
'user_id' => $horario->user_id,
'date_fin IS NOT' => null
]);
This works if I remove the condition between, but if I put it it doesn't give an error but it doesn't return anything.

convert the mysql query to codeigniter 3 model

Convert the MySQL query to Codeigniter Query
$query = "(SELECT content, title, 'msg' as type FROM messages WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'topic' as type FROM topics WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')
UNION
(SELECT content, title, 'comment' as type FROM comments WHERE content LIKE '%" .
$keyword . "%' OR title LIKE '%" . $keyword ."%')";
mysql_query($query);
I have tried to convert it in Codeigniter
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
->from('message')
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->like("msg", $keyword);
->from('topics')
$this->db->or_like('content',$keyword,'after');
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
->from('comment')
The top one is in MySQL and bottom which I try to convert is in Codeigniter I m trying to search the keyword from selected columns from three tables. How I can convert the MySQL to Codeigniter. I'm trying to search the keyword from selected columns from three tables.
How I can convert the MySQL to Codeigniter
Try this
$this->db->select('content, title, msg as type');
$this->db->from('message');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
$query1 = $this->db->get_compiled_select();
$this->db->select('content, title, msg as type');
$this->db->from('topics');
$this->db->like("content", $keyword);
$this->db->or_like('title',$keyword,'after');
$this->db->like("msg", $keyword);
$query2 = $this->db->get_compiled_select();
$this->db->select('content, title, msg as type');
$this->db->from('comment');
$this->db->or_like('content',$keyword,'after');
$this->db->or_like('title',$keyword,'after');
$this->db->or_like('msg',$keyword,'after');
$query3 = $this->db->get_compiled_select();
$result = $this->db->query($query1." UNION ".$query2." UNION ".$query3);
return $result->result();
Note:- If you intend to use this make sure that your both the table column are same sequence and name.

How to combine SQL OR conditions in Product Collection ? Magento?

I want my results to come either from name match OR description match.
$custom_collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToSelect('type')
->addAttributeToSelect('price')
->addAttributeToFilter(array('attribute' => 'name', 'like' => '%' . $queryText . '%'))
->addAttributeToFilter(array('attribute' => 'description', 'like' => '%' . $queryText . '%'))
->addFieldToFilter('attribute_set_id', array(11, 4));
These are the two specific lines I need to merge
->addAttributeToFilter(array('attribute' => 'name', 'like' => '%' . $queryText . '%'))
->addAttributeToFilter(array('attribute' => 'description', 'like' => '%' . $queryText . '%'))
You can use below code for OR condition.
$custom_collection->addAttributeToFilter(
array(
array('attribute'=> 'name','like' => '%' . $queryText . '%'),
array('attribute'=> 'description','like' => '%' . $queryText . '%')
)
);
Try the following:
$collection->addAttributeToFilter(
array(
array('attribute'=> 'name','like' => ''%' . $queryText . '%''),
array('attribute'=> 'description','like' => ''%' . $queryText . '%''),
)
);
This will output a WHERE clause of the format:
WHERE ((name LIKE ''%' . $queryText . '%'') OR (description LIKE ''%' . $queryText . '%'')

Yii: SQL query for getting the top users for every month and top users at the end of year

I am a yiibie, I have a question that I have a table named user_join_event which has id(PK) ngo_id(FK) event_id(FK) date_created date_modified as objects, and I want to get the 5 users Id's(which are repeated the most in this table) for every month. Like January top 5 users, Feb top 5 users and so on and then the top 5 users at the end of the year from this table, like once the year is completed it should give again the top 5 users from all over the month. Please help me with this, how to write an SQL query for this, thank you.
public function actionAllstats()
{
$this->layout='main';
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_created)=:year and MONTH(date_created)=:month',
'param' => array(':year'=>2015, ':month'=>$yourMonth),
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
$this->render('allstats', array("user"=>$user));
}
and this is my view file
<div>
<?php
foreach($user as $show)
{
for($i = 1 ; $i <=12 ; $i++)
{
if($yourMonth == $i)
{
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model))
{
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
}
}
?>
</div>
For the Year you can sue this query for getting the users
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year',
'params' => array(':year'=>2015)
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
and for the month you can do a loop from 1 to 12 using this query and set $yourMonth withe the value in loop
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year and MONTH(date_create)=:month',
'params' => array(':year'=>2015, ':month'=>$yourMonth )
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
Controller action
public function actionAllstats()
{
$this->layout='main';
$myCurrYear = date("Y")
$userYear=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year',
'params' => array(':year'=>$myCurrYear)
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
$this->render('allstats', array("userYear"=>$userYear));
}
View
This view in not based on good pratice, because use access to model inside a view. is a trial for lead you to understand some of the problem related with question.
<?php // this for the twelve month
for($month = 1 ; $month <=12 ; $month++) {
<div>
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_created)=:year and MONTH(date_created)=:month',
'params' => array(':year'=>2015, ':month'=>$month),
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
foreach($user as $show) {
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model)) {
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
</div>
}
?>
<div>
<?php // the for the year
foreach($userYear as $show) {
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model)) {
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
?>
</div>

Opencart retriving data from 2 tables

I´m trying to join 2 tables in opencart to make an sales report that specifies taxes (by class, there can be many tax%) for every order. I can only get the values from 1 table, but not 2.
How should I do this?
<?php $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order`, `" . DB_PREFIX . "order_total`");
$ordersr = array();
// Check if there are any rows returned from the query
if ($query->num_rows > 0) {
// Loop through the returned rows for processing
foreach ($query->rows as $result) {
$ordersr[] = array(
'order_id' => $result['order_id'],
'invoice_no' => $result['invoice_no'],
'total' => $result['total'],
'order_status_id' => $result['order_status_id'],
'date_added' => $result['date_added'],
'date_modified' => $result['date_modified'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname'],
'payment_country' => $result['payment_country'],
'payment_method' => $result['payment_method'],
'payment_code' => $result['payment_code'],
'shipping_method' => $result['shipping_method'],
'shipping_code' => $result['shipping_code'],
'currency_code' => $result['currency_code'],
'currency_value' => $result['currency_value'],
'order_status_id' => $result['order_status_id'],
'date_payed' => $result['date_payed']
);
}
} ?>