In Yii 1.1.x using relational queries, consider the following tables:
Table 'Invoice'
id, original_balance, invoice_date, due_date
Table 'InvoicePayments'
id, invoice_id, payment_amount, old_balance, new_balance, payment_date
Modal invoice.php function relations():
'Payments' => array(self::HAS_MANY, 'InvoicePayments', array( 'id' => 'invoice_id' )
If I want to use a relational query on a particular Invoice object, how can I get the SUM of all InvoicePayments.payment_amount?
Example (doesn't work):
$model = Invoice::model()->with( array( 'InvoicePayments' => array( "??.SUM(payment_amount) )->findByPk(1);
I am finding that without this I have to pull the relational query without the SUM and loop through each InvoicePayments.payment_amount to get the total amount paid towards the invoice.
Any help is appreciated, thanks for looking
Use the Statistical Query STAT provided by Active Record and force it to use the SQL SUM function by assigning its select option :
invoice.php :
public function relations()
{
return array(
'payments' => array(self::HAS_MANY, 'InvoicePayments', array( 'id' => 'invoice_id' )
'paymentsSum'=>array(self::STAT, 'InvoicePayments', 'invoice_id', 'select' => 'SUM(payment_amount)'),
);
}
Then you can use it to load one or many models by using any of the lazy or eager approache, here is 3 different examples :
// the lazy loading approach
$invoice=Invoice::model()->findByPk(10);
$total = $invoice->paymentsSum;
// the eager loading approach
$invoices=Invoice::model()->with('paymentsSum')->findByPk(10);
$total = $invoice->paymentsSum;
// the eager loading approach to load all invoices
$invoices=Invoice::model()->with('paymentsSum')->findAll();
$total_of_invoice_10 = $invoices[10]->paymentsSum;
Related
I have an existing cakephp (version 2) controller index function doing this:
$options = ['Person.name LIKE' => $term];
$this->set('people', $this->Paginator->paginate($options));
resulting in a paginated table in the view.
My Person model references a child model of Appointment, where one person has many appointments like so:
public $hasMany = [
'Appointment' => [
'className' => 'Appointment',
'foreignKey' => 'person_id',
'dependent' => false
]
]
I now need to add a Person's Oldest Appointment Date column to my table, i.e. if working with raw SQL I might do this:
select
Person.id,
Person.name,
(select
min(Appointment.Date) from Appointment
where Appointment.person_id = Person.id
) as OldestAppointmentDate
from Person
where Person.name like 'foo%'
How can I modify the paginate() parameters so that this new field is included in the results and is sortable by paginate in the usual way?
The most simple way would probably be to use a virtual field, which you can then include in the paginators fields option, something like:
// in Model/Person.php
public $virtualFields = array(
'OldestAppointmentDate' => '
select
min(Appointment.Date)
from
Appointment
where
Appointment.person_id = Person.id
';
);
// in your controller action
$this->Paginator->settings['fields'] = array(
'Person.id',
'Person.name'
'Person.OldestAppointmentDate'
);
// ...
That will include the subquery and create the required aliases accordingly, and things get stitched together automatically so that the results look like as if OldestAppointmentDate is an actual field of Person, and you can refer to it in the paginator helper like any other field, ie:
$this->Paginator->sort('Person.OldestAppointmentDate');
See also
Cookbook > Models > Virtual fields
Cookbook > Core Libraries > Components > Pagination > Query Setup
I am beginner in Yii, So I am asking this question.
I have three different tables.
First Table
First table is language(id, language_name)
// id is primary key.
Second Table
Second Table is verse(id, topic_id, surah_id, verse_text)
// id is primary key,
Third Table
Third table is verse_translations(id, verse_id, language_id, translations_text)
// id is primary key, language_id is foreign key references with language table,
// verse_id is foreign key references with verse table.
Now My Question is.
I want to get the list of languages of available translations with specific verse_id. ? For that i want to make relations in verse model file that will return an available languages in my view, so how to get result in view also.? and what will be the changes in verse model, view and controller if any changes occur.
I have written MySQL query which is in below.
SELECT language.language_name from language
Inner Join verse_translations ON verse_translations.language_id = language.id
Where verse_translations.verse_id = 1
But i need this in Yii.
I have generated verse model through gii code generator.
My Verse Model Relations function.
public function relations()
{
return array(
'sorah' => array(self::BELONGS_TO, 'Sorah', 'sorah_id'),
'topic' => array(self::BELONGS_TO, 'Topic', 'topic_id'),
'verseFeedbacks' => array(self::HAS_MANY, 'VerseFeedback', 'verse_id'),
'verseImages' => array(self::HAS_MANY, 'VerseImages', 'verse_id'),
'verseLinks' => array(self::HAS_MANY, 'VerseLinks', 'verse_id'),
'verseTafseers' => array(self::HAS_MANY, 'VerseTafseer', 'verse_id'),
'verseTranslations' => array(self::HAS_MANY, 'VerseTranslations', 'verse_id'),
'language_name' => array(self::HAS_MANY, 'Language', 'id'),
);
}
I wrote you your sql code,
$result = Yii::app()->db->createCommand()
->select('l.language_name')
->from('language l')
->join('verse_translations vt' , 'l.id = vt.language_id ')
->join('verse v' , 'vt.id = v.id')
->where('v.id = :var' , array(':var'=>1))
->queryAll();
btw I didn't read all your post, just read your sql :D
UPDATE: if you define your relations in mysql before you generate model files, you get the relations generated for you.this is the easiest way possible, then you can do this:
$vers = Ver::model()->findByPk(1);
$allLangs = $vers->language_name; // this will give you an array of Language Model back
let me know what did
cheers
You can easily get the list of available translated languages from language table.
Let see first.
'verseTranslations' => array(self::HAS_MANY, 'VerseTranslations', 'verse_id'),
this relation will take all the rows of verse translation of specific verse id, mean if you have 10 different translation in 10 different languages with verse_id 1, it will display all. Now you can see in question verse_translation table have language_id.
So we can get all languages by that language_id.
Now we make another relation which is relating to language_id through verseTranslations, and this relation will display all the translated languages.
'verse_lang' => array(self::HAS_MANY, 'Language', array('language_id'=>'id'), 'through'=>'verseTranslations'),
So as i have written a Sql Query is equivalent to these two relations.
'verseTranslations' => array(self::HAS_MANY, 'VerseTranslations', 'verse_id'),
'verse_lang' => array(self::HAS_MANY, 'Language', array('language_id'=>'id'), 'through'=>'verseTranslations'),
On view, we can easily access it by var_dump($data->verse_lang)
That's it.
for understanding relations. You may read carefully to this link.
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through
Hope it will help.
If you need any help then leave a message in comment box.
Thanks.
At first take a look at the following model structure:
Model Building:
id
name
Model BuildingRange:
id
building_id
postalcode
Ok, so BuildingRange $belongsTo Building and Building $hasMany BuildingRange. Should be clear til' here.
Now let
$current_postalcode="12345";
I know want to do something like this in the BuildingController:
$this->paginate('Building',array('Building.BuildingRange.postalcode'=>$current_postalcode));
In text: I want to select all buildings for that an entry "BuildingRange" with $current_postalcode exists. How do you do that?
I appreciate your help!
When dealing with such a hasMany association, CakePHPs auto-magic needs two queries, one on the Building table, and one on the BuildingRange table. When passing conditions via the pagiante method, these conditions will be passed to the first query, and thus this it will fail since the associated models table isn't joined.
This problem can be solved on a few different ways, one would be using an ad-hoc join, for example:
$this->paginate = array
(
'joins' => array
(
array
(
'table' => 'building_ranges',
'alias' => 'BuildingRange',
'type' => 'LEFT',
'conditions' => array('BuildingRange.building_id = Building.id')
)
)
);
$this->paginate('Building', array('BuildingRange.postalcode' => $current_postalcode));
This would result in a query that looks something like this:
SELECT `Building`.`id`,
`Building`.`name`
FROM `buildings` AS `Building`
LEFT JOIN `building_ranges` AS `BuildingRange`
ON ( `BuildingRange`.`building_id` = `Building`.`id` )
WHERE `BuildingRange`.`postalcode` = '12345'
LIMIT 20
Note that in the conditions passed to the paginate method there is no need to reference the BuildingRange model through the Building model, ie no need to use Builduing.BuildingRange (that wouldn't work anyway).
ps, it's always good to mention the CakePHP version you are using!
I have two models in an 1:n relation and I just want to load the count of the related items.
First one is the table/model "Ad" (one) which is related to "AdEvent" (many). AdEvents has a foreign key "ad_id".
In the controller I can use it that way and it loads the related AdEvent-records.
$this->Ad->bindModel(array('hasMany' => array(
'AdEvent' => array(
'className' => 'AdEvent',
'foreignKey' => 'ad_id',
))));
Now I just need the count without the data and I tried with param "fields" and "group" a COUNT()-statement, but in that case the result is empty. I also changed the relation to "hasOne", but no effect.
Any idea how to use the Cake-magic to do that?
EDIT:
With simple SQL it would look like this (I simplyfied it, a.id instead of a.*):
SELECT a.id, COUNT(e.id) AS count_events
FROM cake.admanager_ads AS a
JOIN ad_events AS e ON e.ad_id = a.id
GROUP BY a.id
LIMIT 50;
You can always do a manual count of course. This is what I almost always end up doing because I almost always have the data loaded already for some other purpose.
$Ads = $this->Ad->find('all')
foreach ($Ads as $Ad) {
$NumAdEvents = array(
$Ad['Ad']['id'] => sizeof($Ad['AdEvents']),
)
}
debug($NumAdEvents);
die;
Or you can use a find('count'):
$id_of_ad = 1; //insert your ad id here, or you can search by some other field
$NumAdEventsAtOneAd = $this->AdEvent->find('count', array('conditions' => array(
'AdEvent.ad_id' => $id_of_ad,
)));
debug($NumAdEventsAtOneAd);
die;
I'm using CakePHP 1.3.8, and I've installed the CakeDC Search plugin. I have a Tutorial model, which is in a HABTM relationship with a LearningGoal model.
I have a search action & view in the Tutorials controller with which I can successfully search fields in the Tutorial model. I'd also like to filter my tutorial search results using LearningGoal checkboxes on the same form. I've tried adding various parameters to Tutorial's $filterArgs and TutorialsController's $presetVars. I've also tried moving the relevant $filterArgs to the LearningGoal model. I have not yet been able to successfully trigger the entry for learning goals in $filterArgs.
I think I must be missing something obvious. Or maybe the Search plugin doesn't support what I'm trying to do. Does anyone know how to use this plugin to search on associated models?
So here's what I've figured out. You can combine what's below with the Search plugin directions to search on related models.
The $filterArgs piece in the Tutorial model must look like this:
var $filterArgs = array(
array('name' => 'LearningGoal', 'type' => 'subquery', 'method' => 'findByLearningGoals', 'field' => 'Tutorial.id'),
);
Here's the supporting function in the Tutorial model:
function findByLearningGoals($data = array()) {
$ids = explode('|', $data['LearningGoal']);
$ids = join(',', $ids);
$this->LearningGoalsTutorial->Behaviors->attach('Containable', array('autoFields' => false));
$this->LearningGoalsTutorial->Behaviors->attach('Search.Searchable');
$query = $this->LearningGoalsTutorial->getQuery('all',
array(
'conditions' => array('LearningGoalsTutorial.learning_goal_id IN (' . $ids . ')'),
'fields' => array('tutorial_id'),
)
);
return $query;
}
In TutorialsController, $presetVars should look like this:
public $presetVars = array(
array('field' => 'LearningGoal', 'type' => 'checkbox', 'model' => 'Tutorial'),
);
And in my search action in TutorialsController, I did this:
$this->LearningGoal = $this->Tutorial->LearningGoal;
The Prg component seems to need that.
I am using CakePHP version 2.X
Every time I come to do this in a project I always spend hours figuring out how to do it using CakeDC search behavior so I wrote this to try and remind myself with simple language what I need to do. I've also noticed that although Michael is generally correct there is no explanation which makes it more difficult to modify it to one's own project.
When you have a "has and belongs to many" relationship and you are wanting to search the joining table i.e. the table that has the two fields in it that joins the tables on either side of it together in a many-to-many relationship you want to create a subquery with a list of IDs from one of the tables in the relationship. The IDs from the table on the other side of the relationship are going to be checked to see if they are in that record and if they are then the record in the main table is going to be selected.
In this following example
SELECT Handover.id, Handover.title, Handover.description
FROM handovers AS Handover
WHERE Handover.id in
(SELECT ArosHandover.handover_id
FROM aros_handovers AS ArosHandover
WHERE ArosHandover.aro_id IN (3) AND ArosHandover.deleted != '1')
LIMIT 20
all the records from ArosHandover will be selected if they have an aro_id of 3 then the Handover.id is used to decide which Handover records to select.
On to how to do this with the CakeDC search behaviour.
Firstly, place the field into the search form:
echo $this->Form->create('Handover', array('class' => 'form-horizontal'));?>
echo $this->Form->input('aro_id', array('options' => $roles, 'multiple' => true, 'label' => __('For', true), 'div' => false, true));
etc...
notice that I have not placed the form element in the ArosHandover data space; another way of saying this is that when the form request is sent the field aro_id will be placed under the array called Handover.
In the model under the variable $filterArgs:
'aro_id' => array('name' => 'aro_id', 'type' => 'subquery', 'method' => 'findByAros', 'field' => 'Handover.id')
notice that the type is 'subquery' as I mentioned above you need to create a subquery in order to be able to find the appropriate records and by setting the type to subquery you are telling CakeDC to create a subquery snippet of SQL. The method is the function name that are going to write the code under. The field element is the name of the field which is going to appear in this part of the example query above
WHERE Handover.id in
Then you write the function that will return the subquery:
function findByAros($data = array())
{
$ids = ''; //you need to make a comma separated list of the aro_ids that are going to be checked
foreach($data['aro_id'] as $k => $v)
{
$ids .= $v . ', ';
}
if($ids != '')
{
$ids = rtrim($ids, ', ');
}
//you only need to have these two lines in if you have not already attached the behaviours in the ArosHandover model file
$this->ArosHandover->Behaviors->attach('Containable', array('autoFields' => false));
$this->ArosHandover->Behaviors->attach('Search.Searchable');
$query = $this->ArosHandover->getQuery('all',
array(
'conditions' => array('ArosHandover.aro_id IN (' . $ids . ')'),
'fields' => array('handover_id'), //the other field that you need to check against, it's the other side of the many-to-many relationship
'contain' => false //place this in if you just want to have the ArosHandover table data included
)
);
return $query;
}
In the Handovers controller:
public $components = array('Search.Prg', 'Paginator'); //you can also place this into AppController
public $presetVars = true; //using $filterArgs in the model configuration
public $paginate = array(); //declare this so that you can change it
// this is the snippet of the search form processing
public function admin_find()
{
$this->set('title_for_layout','Find handovers');
$this->Prg->commonProcess();
if(isset($this->passedArgs) && !empty($this->passedArgs))
{//the following line passes the conditions into the Paginator component
$this->Paginator->settings = array('conditions' => $this->Handover->parseCriteria($this->passedArgs));
$handovers = $this->Paginator->paginate(); // this gets the data
$this->set('handovers', $handovers); // this passes it to the template
If you want any further explanation as to why I have done something, ask and if I get an email to tell me that you have asked I will give an answer if I am able to.