So here's the scenario:
I have two table, Issue & Project.
A Project can have many Issue and an Issue can exactly one project.
Since Issue is many to one, do you have to define it?
Cause I know in Project Model I have:
public function relations()
{
return array(
'issues' => array(self::HAS_MANY, 'Issue', 'project_id'),
'users' => array(self::MANY_MANY, 'User', 'tbl_project_user_assignment(project_id, user_id)'),
);
}
For Issue Model I have nothing but foreign keys:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'project' => array(self::BELONGS_TO, 'Project', 'project_id'),
);
}
I'm guessing anything to one relationship does not need to be define?
Thank you in advance.
BTW, I'm doing agile Yii book and I ended up asking myself this question.
There's a has-one option in AR class (http://www.yiiframework.com/doc/guide/database.arr).
But is this case optional for some reason?
It helps me to think of the difference between BELONGS_TO and HAS_ONE as "where is the foreign key stored"? If the Project model stored "Issue_Id" then potentially Issue could have many Projects. You use the HAS_ONE relationship to state that even if Issue COULD have many projects, it only has ONE.
However, the more common case is if you are storing the Project_Id in the Issue model (and I assume you are). Then you have to use the BELONGS_TO relationship. It appears you have defined the relationships correctly above.
Someone posted a similar question relating to Yii relations here that I helped answer:
yii - using relation HAS_ONE to get data from the related table to display in list page
As to your concern about "needing" to define relationships, you don't "need" to define any. You could write your own SQL queries to do the same thing. The ActiveRecord relations are just a convenience thing to make querying for related records simpler. If you are never going to look up an Issue's Project, then you don't "need" to define the "project" BELONGS_TO relationship.
Without actually seeing your database structure it looks to me like you have everything set up correctly. You can now easily make both $issue->project and $project->issues "lazy" relational queries, taking full advantage of the power of the Relational Active Record. Cheers and good luck with project!
In your Issue model you already have the relation specified as BELONGS_TO the project model.
I also just got the new yii-book. It helped me alot!
Happy coding :)
Related
Which relation to use in Laravel to bind two table through third?
When Doctors can be assigned to some Centers. The intermediate table will be as:
doctor_id | center_id
How to create model in Laravel for this case?
You don't need a model for the intermediate table, simply use attach
Example:
$center = Center::create();
$doctor = Doctor::find(1);
$doctor->centers()->attach($doctor->id);
This is a very simple example but should give you the idea, of how to approach it.
All of it of course requires you have set up your Center and Doctor model with the correct many to many relations
Doctor.php model:
public function centers()
{
return $this->belongsToMany(Doctor::class);
}
See the documentation, for more information.
You could obviously create a model called DoctorsCenter and create it manually by doing this, whenever you want to attach a relation.
DoctorsCenter::create(['center_id' => $center->id, 'doctor_id' => $doctor->id]);
I don't see any good reason for doing this, and would not recommend it.
You can use hasMany or belongsTo relationship of Laravel.
See the laravel documentation, for more information
I'm trying to build a role-based user management but segmented by resource of many types.
I have this relational model:
I need to show in the user profile management view something like this:
But I don't want to make queries like:
RoleUser::where('user_id',1)->get();
I would like to use the many-to-many polymorphic relationship to take advantage of the Eager/Lazy loading of Laravel, but I don't know to do it.
An other interesting feature to take into account, is that I don't want to store in the database the types like App\Models\Event, App\Models\Article or App\Models\Photo but the map is not working well for me (because the relationships aren't set properly).
//AppServiceProvider::boot()
Relation::morphMap([
'event' => Event::class,
'race' => Race::class,
]);
Any idea?
Try this
//AppServiceProvider::boot()
Relation::morphMap([
'event' => App\Models\Event::class,
'race' => App\Models\Race::class,
]);
I have two tables that need to be linked: 'user' and 'dealer'. The relation table is 'user_dealer'.
I found using $crud->set_relation_n_n() works well for edit and add screens to restrict which records are edited and added, like this:
$crud->set_relation_n_n('Dealers', 'user_dealer', 'dealer', 'user_id', 'dealer_id', 'dealer', null, array('id' => $this->session->userdata('dealer_id')));
But for some reason, this does not work for the LIST grid.
I tried $crud->where() but this does not work, as it does not have the column from the relation table there.
Can anybody help, please?
Apparently this is not possible, so I had to write a custom model that extends the Grocery Crud model and do what I needed to do.
I have two models: Bar HABTM Foo. Now I have bars_foos join table with some additional fields.
When I add new Bar with some Foo associations or vice versa, I need to run many validation checks, whether the new associations are kosher. Checks are based on the additional fields defined and already saved associations.
Where should I run these validations? In Bar/Foo controller? Or should I create BarsFoo model with validation rules?
When I keep HABTM relationship to get all the auto-magic from Cake, I cannot find a way to tell Cake to use my own predefined BarsFoo model with validations rules. Cake creates its own virtual model and ignores mine.
Or should I (in this specific case) break HABTM into hasMany-belongsTo-hasMany relationship, where I can use my own BarsFoo model?
You can define your join model using the with key and create your validations there:
public $hasAndBelongsToMany = array(
'Bar' => array(
…
'with' => 'BarFoos'
)
);
http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM
I'm looking for a suggestion on how to set up two models, Teacher and Subject. A Teacher can have many Subjects, and a Subject can have many Teachers. Another thing to consider in the relationship between the two models is that a Teacher can create a Subject and add other Teachers to the Subject.
I think I'm solid on the basics of the set up for each model:
for teacher.rb:
has_many :subjects
for subject.rb:
has_many :teachers
and the teachers table should have a subject_id column and the subject table should have a teacher_id column.
What I'm not sure about is how to set up the views (and corresponding controller methods) to allow the addition of a Teacher to a Subject.
Any suggestions (or links to examples) are greatly appreciated. I haven't been able to find anything on this exact case.
current set up:
standard CRUD for a Student object
standard CRUD for a Project object
I'm likely missing something simple in how to tie these models together (other than the part of changing has_many to habtm) and getting records into the subjects_teachers table, and I still can't find a good example...
You need to build the relational table between them. It's impossible to have a many-many relationship without a rel table
First off though, it's a has_and_belongs_to_many :subjects and has_and_belongs_to_many :teachers (commonly referred to as habtm)
http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association
run
rails g migration subjects_teachers
open up the migration:
create_table :subjects_teachers, :id => false do |t| # ID => FALSE = IMPORTANT
t.references :subject
t.references :teacher
# NO TIMESTAMPS
end
run
rake db:migrate and you should be set!
then
see these railscasts for setting up your controllers
http://railscasts.com/episodes/17-habtm-checkboxes
http://railscasts.com/episodes/47-two-many-to-many