Relationship issue in YII - yii

I Have a GetStudents function in Agent model. where I fetch the students related to the agents.
But I want to show more fields of students from another table
Eg
**Agent table** (agent has students)
agent_id
**student table**
STUDENTID pkey
agent_id
**relation table** (this table creates relation between student and household)
StudentID HOUSEHOLDID
**HOUSEHOLD TABLE**
HouseHOLDID Householdname
I want to fetch householdname when I fetch all student details.
really looking bazzare to me as I am newbie to YII
MY function in agent model.
public static function getStudents($id) {
$relationships = Relationship::model()->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id));
//$relationships=sort($relationships);
// Generate relationship array
//print_r($relationships);
foreach ($relationships as $relationship) {
$in[] = $relationship->destination;
}
// Generate db condition
$criteria = new CDbCriteria;
if (! isset($in) || ! is_array($in) || sizeOf($in) == 0) {
$in[] = -999;
}
$criteria->addInCondition('StudentID', $in, 'OR');
return new CActiveDataProvider('Student', array(
'criteria' => $criteria,
'sort'=>array('defaultOrder'=>array(
'StudentID'=>CSort::SORT_DESC,
)),
));
}
My code to fetch data in by passing ID into it
<?php $this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes' => array(
array(
'label' => 'Agent Details',
'type' => 'raw',
'value' => '',
'cssClass' => 'heading',
),
'agent_id',
'user.email',
'first_name',
'last_name',
'company',
'phone',
),
)); ?>
Any help would be greatly appreicated.
Thanks
Ab

First you should make relation with student to relation table in relations array in relation model like this ..
'student'=>array(self::BELONGS_TO, 'Student', 'StudentID'), //after belongs to student is model class name
'household'=>array(self::BELONGS_TO, 'HOUSEHOLD', 'HOUSEHOLDID'),//after belongs to HOUSEHOLD is model class name
And then you can fetch all record with active record like this...
$relationships = Relationship::model()->with('student','household')->findAll('type = :type AND source = :agent_id', array(':type' => 2, ':agent_id' => $id));

Related

Collect data from three table in yii1?

I am new in YII1. I have three tables: Jd, jda and user. Relation with jd and jda is
'jobDescription'=> array(self::HAS_MANY, 'JobDescriptionAssignment', /*array('id'=>'job_desc_id')*/'id'),
and the relation between jda and user is
'users' => array(self::BELONGS_TO, 'User', 'user_id'),
My tables are :
jd->id,name
jda->id,jd_id,user_id
user->id,supervisor_id
supervisor_id comes from user table id. Now I want to show data from jd model those user whose supervisor_id is logged in id.
see this topic Yii Framework : Join table (or other SQL) in data provider?
public function search(){
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('status',$this->status,true);
$criteria->compare('createDate',$this->createDate,true);
$criteria->compare('updateDate',$this->updateDate,true);
$criteria->compare('remark',$this->remark,true);
$criteria->with = array('cateLang' => array(
'condition' => 'cateLang.id = 1 OR cateLang.id = 2',
'order' => 'cateLang.id ASC'
));
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
-
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
array(
'name' => 'FrenchTitle'
'value' => '(isset($data->cateLang[0])) ? $data->cateLang[0]->name : "no Title"',
),
array(
'name' => 'EnglishTitle'
'value' => '(isset($data->cateLang[1])) ? $data->cateLang[1]->name : "no Title"',
),
'createDate',
'updateDate',
'remark',
array(
'class'=>'CButtonColumn',
),
),
));

How can i get first and last record id in yii CGridview?

I want first and last record id form $dataprovider which is passed to gridview which i need to pass to this link.
array(
'name' => 'msg',
'value' => 'CHtml::link(substr(strip_tags($data->msg),0,30)." .....",Yii::app()->createUrl("Mail/view",array("id"=>$data->primaryKey,"flag"=>"inbox","tab"=>'.$tab.',"category"=>'.$category.')))',
'type' => 'raw',
'header' => 'Message',
),
Declare two attributes in your controller.
public $first=null;
public $last=null;
Define a function in controller to render your link
public function renderMailViewLink($data,$row){
// you can return anything you want here. whether a link or whatever
// access $this->first->id , $this->last->id
return CHtml::link($data->anyAttribute,array('someRoute','id'=>$data->id,'first'=>$this->first->id))
}
CActiveDataProvider has a method getData(), which return array of all active records.
in actionIndex
$dataProvider = $model->search()
$data = $dataProvider->getData();
$this->first = reset($data );
$this->last = end($data);
And finally in your view
array(
'name' => 'msg',
'value' => array($this,'renderMailViewLink'),
'type' => 'raw',
'header' => 'Message',
),
Please note this code is not tested. But thats how it can be achieved

Kohana ORM relations - how

I am trying to build a simple relation between two tables.
Unfortunately, the ORM searches for another column from the parent model:
<?php
class Model_Hreflang extends ORM {
[...]
protected $_table_columns = array(
'id' => NULL,
'domain_id' => NULL,
'country_code_id' => NULL,
'language_code_id' => NULL
);
protected $_has_many = array(
'cc' =>
array(
'model'=> 'Country2',
**'WHAT TO PUT HERE'** => 'country_code_id',
'foreign_key' => 'country_code'),
}
When trying to get a related record to the first table, the query is made like
"hreflang".id = "country2".country_code
and I need to change it, for example to
"hreflang".country_code_id = "country2".country_code
Anyone managed to do it by the ORM?
Thanks!
Anton
I think you schould set it by belongs to
protected $_belongs_to = array('cc' => array('model' => 'Country2', 'foreign_key' => 'country_code'));
read more here: http://kohanaframework.org/3.0/guide/orm/relationships

CakePHP use JOIN in find method

i am newbie in cakephp and trying to implement this query
SELECT DISTINCT textmessage.mobileNo FROM textmessage
JOIN contacts
ON textmessage.User_id=contacts.User_id AND textmessage.mobileNo = Contacts.mobileNo
i am expecting only one result here .. want to implement this query in textMessage Controller ... i have never use join query before in CAKEPHP... i have actually a mobileNo field in both the tables and i want to retrieve the mobileNo if the mobileNo of textmessage table is also in Contacts table
here is what i have modified your query according to my requirments ..
$this->bindModel(array('belongsTo' => array('Contact' => array('className' => 'Contact',
'foreignKey' => false,
'conditions' => array('Message.user_id = Contact.user_id','Message.mobileNo = Contact.mobileNo')))), true);
return $message_details = $this->find('all', array('conditions' => array(),
'fields' => array('DISTINCT mobileNo')));
Put the following code in your controller's code:
If you need only single record:
function test1()
{
$this->TextMessage->bindModel(array('belongsTo' => array('Contact' => array('className' => 'Contact',
'foreignKey' => false,
'conditions' => array('TextMessage.user_id = Contact.user_id')))), false);
$message_details = $this->TextMessage->find('all', array('conditions' => array(),
'fields' => array('DISTINCT mobileNo')));
}
If you have multiple text messages corresponding to each contact then try the following:
function test2()
{
$this->Contact->bindModel(array('hasMany' => array('TextMessage' => array('className' => 'TextMessage',
'foreignKey' => false,
'conditions' => array('TextMessage.user_id = Contact.user_id'),
'fields' => array('DISTINCT mobileNo')))
), false);
$message_details = $this->Contact->find('all', array('conditions' => array()));
}
You can also write the association in your model. I gave you an example to dynamically join any table on the fly.
According to your edited question, if you don't need two arrays. Use query() function.
Hope this will fulfill your requirement.

Kohana 3.2 ORM many-to-many - wrong field names

I trying to make many-to-many relation between 2 models: Users_Role and Users_Right
class Model_Users_Role extends ORM{
protected $_has_many = array(
'rights' => array(
'model' => 'users_right',
'through' => 'users_roles_rights',
),
);
}
class Model_Users_Right extends ORM{
protected $_has_many = array(
'roles' => array(
'model' => 'users_role',
'through' => 'users_roles_rights',
),
);
}
I'm trying to do this:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$right->add('roles', $role);
Error:
Database_Exception [ 1054 ]: Unknown column 'role_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_right_id`, `role_id`) VALUES ('1', '1') ]
I tryed to make it on the other side:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$role->add('rights', $right);
New error:
Database_Exception [ 1054 ]: Unknown column 'right_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_role_id`, `right_id`) VALUES ('1', '1') ]
I expected ORM to use users_role_id and users_right_id field names in pivot table, but it uses wrong name of far key? Where I have made a mistake?
Check out where the default values are set.
Try this:
class Model_Users_Role extends ORM{
protected $_has_many = array(
'rights' => array(
'model' => 'users_right',
'far_key' => 'users_right_id',
'through' => 'users_roles_rights',
),
);
}
class Model_Users_Right extends ORM{
protected $_has_many = array(
'roles' => array(
'model' => 'users_role',
'far_key' => 'users_role_id',
'through' => 'users_roles_rights',
),
);
}
Kohana does not check that the relationship does not already exist.
Either enforce this in the database table with a composite unique key on the two foreign key columns, or make your code check that the relationship does not already exist before adding.