YII: Dropdownlist with relation - yii

DB table:
Mcourse(Master course )-> contains Course Names
Lcourse(Linked
Course- courses belongs to a college) -> contains foreign key
Mcourse_Id. & college Id.
Nw the problem is
I want to display list of courses available in a college using dropdownlist.
So sql query is:
select Lcourse_Id, Mcourse_Name* from Lcourse inner join Mcourse on Lcourse_Mcourse_Id=Mcourse Id..
*Id & value pair for dropdownlist
I could do this usin createCommand..Its working pretty fine. But i cant do this usin Relations ..Help me.

Let's imagine for a minute that your Mcourse table is called courses and model for that table is called Courses, your Lcourse table is called courses_colleges and your colleges table is colleges and model for that table is Colleges
Now, You should have Courses model with relations:
public function relations() {
return array(
'colleges' => array(self::MANY_MANY, 'Colleges', 'courses_colleges(course_id, college_id)')
);
}
Your Colleges model should have similar relations:
public function relations() {
return array(
'courses' => array(self::MANY_MANY, 'Courses', 'courses_colleges(college_id, course_id)')
);
}
Now if you want to print out a dropdown with all courses available for a certain college. In your controller action method get the model of that college including its courses:
public function actionShow() {
$id = 1; // We set just some sample id. You could get it from request ofc.
$college = Colleges::model()->with('courses')->findByPk($id);
$this->render('show', array('college'=>$college));
}
Now in your view print out this:
echo CHtml::dropDownList('courses', '', CHtml::listData($college->courses, 'id', 'name'));
Where 'id' and 'name' are columns of your Courses model.
Something like that.

The error is in the listData() function in your view, specifically that you don't have a mc_Id in your Lcourse model.
As you haven't clarified the model that each of those relationships are assigned with, it's impossible to guess what you should substitute for 'mc_Id' in your view - check your Lcourse model to determine the proper column name.

Related

how to related two fields whose they are not principal keys?

I have 3 tables:
class users
columns={
name=fields.char(....
sucursal_user:fields.many2one('sucursales',...}
users()
class sucursales
columns={
name=fields.char(....
}
sucursales()
class orders
columns={
name=fields.char(....
sucursal_order:fields.many2one('sucursales',...}
orders()
How I can list if I log into the system and I am form 'italy's sucursal I want to list all the orders from Italy
So I need to list users and orders tables where sucursal_user and sucursal_order are equals.
I made a query and works but I don't know how to do it in openerp.
select * from res_users, ordenes_orden
where sucursal_u = sucursal
To view the users and orders related for a particular sucursales record, you can create a one2many field such that those values are shown to you.
class sucursales
columns = {
'user_ids': fields.one2many('res.users', 'sucursal_user', string="Related users"),
'order_ids': fields.one2many('sale.order', 'sucursal_order', string='Related Orders'),
}

Model relationship with eloquent

I have the following table structure :
Artists
id
name
picture
Entry
id
dj_id
producer_id
dj_id and producer_id field in most cases won't be the same, but it might happen. So I've set both field to be foreign keys on the artists_id field.
So in my Entry model, I have this function :
public function dj()
{
return $this->hasOne('Artist', 'id', 'dj_id');
}
This doesn't really work. It keeps returning the artist with id "1" even if the dj_id equals "5". Code sample :
$test = Entry::find(1);
var_dump($test->dj_id); // shows 5
var_dump($test->dj->id); // shows 1
What am I doing wrong ?
Ok so I figured it out, I had to change my dj relation to
return $this->belongsTo('Artist', 'dj_id', 'id');

Joining table not directly related to main table in cakephp

I have three tables whose structure is is similar to below :
employees offices postings
________ ________ ___________
id id employees_id
name name offices_id
So I want to know how can I get the office name from Employee model. Putting office within $hasOne array shows Unknown column 'office.employees_id' in 'on clause'. What should I do to get the office name in the results ?
If you want to stick to your database, you might use has and belongs to many relation.
In employee.php:
public $hasAndBelongsToMany = [
'Office'=> [
'foreign_key' => 'employees_id',
'joinTable' => 'postings',
'associationForeignKey' => 'offices_id',
]
];
Then you can get office from employee model.
What I really want to suggest is that put a column office_id in employees table, and put
$public $belongsTo = ['office'];
in your employee model.
PS: Brackets [] is supported in php 5.4 or newer , if you are using php 5.3 or lower, you may want to replace it with array().

Select distinct active record

I have a model called Shops with an attribute called brands, brands is a text field and contains multiple brands. What i would like to do is select all unique brands and display them sorted in alphabetic order
#brands = Shop.all(:select => 'distinct(brands)')
What to do from here?
If Shop#brands can hold multiple values like for example: "rony, hoke, fike", then I can reluctantly suggest doing something like this:
#brands = Shop.all(:select => 'brands').each { |s|
s.brands.split(',').map { |b|
b.strip.downcase
}
}.flatten.uniq.sort
BUT, you should really think about your data model here to prevent such hackery. You couuld break out the brands into it's own table + model and do a many to many relationship with Shop.

Getting data with CActiveDataProvider in yii

I have 3 tables, standart relation MANY-TO-MANY
Users(id,...) -> Users_Has_Courses(Users_id, Courses_id) -> Courses(id,...)
Courses Model has next relation
'users' => array(self::MANY_MANY, 'Users', 'users_has_courses(Courses_id, Users_id)')
Users Model has next relation
'courses' => array(self::MANY_MANY, 'Courses', 'users_has_courses(Users_id, Courses_id)')
Please, say how I can get list of courses, on which user with specified "id" hasn't been subscribed with CActiveDataProvider ?
Otherwords, I need an analogue of this plain SQL query
select * from Courses where id not in (select Courses_id from users_has_courses where Users_id = 2)
thanks for the help
Instead of a regular "relation", try a parametrized Named Scope to encapsulate the query. In your Courses model, add this scope function to get a list of all the courses the user is not in:
public function userNotIn($user_id)
{
$criteria=new CDbCriteria();
$criteria->condition .= 't.id NOT IN (SELECT users_has_courses.Courses_id FROM users_has_courses WHERE users_has_courses.Users_id = :userid)';
$criteria->params[':userid'] = $user_id;
$this->getDbCriteria()->mergeWith($criteria);
return $this;
}
Then you should be able to do this:
$coursesNotIn=new CActiveDataProvider(Courses::model()->userNotIn($user->id));
This code is completely untested, but it should work in principle. I do this sort of thing often when I have a complex query but I still want to use the AR features, like CActiveDataProvider. Read more about "named scopes" here:
http://www.yiiframework.com/doc/guide/1.1/en/database.ar#parameterized-named-scopes
Good luck!