CakePHP relationship scenario - php

I'm trying to figure out the appropriate relationship setup/schema for the following scenario and I suppose I'm a bit unclear as to the relationships themselves.
My models: Accident and People.
An accident may involve many people. A person may be related to many accidents.
For example: An accident happens to Abe and Bob. Abe may be the related to multiple accidents.
I have an accidents table, a people table and an accidents_people table with the appropriate schema. I want the user to be able to add an accident independently of a person, and a person independently of an accident, and then when they edit an accident, link it to multiple people. Is this possible?
$people = $this->Accident->Person->find('list'); //should give me list of all people
$this->set('people', $people); //should allow me to access a list of all people in view

TLDR:
What you're describing is the "Has and Belongs To Many" relationship (also known as HABTM):
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
Note / Another option:
Another option is the HasMany Through, which is basically HABTM, but with a model specifically for the join table. This allows a bit more flexibility if you need more than just the 3 fields in your join table (id, person_id, and accident_id)
Model convention:
If you're following the CakePHP Model and Database Conventions, your "People" model should really be "Person".
It's "okay" to use non-standard, but if you're learning Cake, you're better off trying to stick to them for now.
(looking at your code, which correctly uses "Person" as the model, I assume you just typed it wrong in your description)

Related

how can i make a relation between master calss and student in my platform

i want to create a platform by laravel 6 included classes students an masters
masters can put the student's scores and the students can see them in their profile...
there is a many to many relation between classes and masters and between student and classes too.
the masters an students are not seperated and all of them store in user table and determine by his role_id
my big issue is uploading of scores by masters... i am extremely confused
has any one any idea ?
What you might want to simplify things is an associative table of users, classes, and scores (I've drawn a diagram for you https://dbdiagram.io/d/5e9787f039d18f5553fdabb1). With this table, you can query pretty much all you could ever want.
Now all you need to do is configure privileges based on user role. A master can read from and write to all class_user_score entities where if there is a record of him being in a class, he can read and CRUD all class_user_score entities with the same classId. A student can only read class_user_score entities with his userId in them.
Unfortunately, I can't help you with the Laravel implementation (they also call an associative table a pivot table for some weird reason) since I'm more of a React, Nodejs type of guy, but I hope this at least helps you to reason about the problem.

Laravel many to many relashionship

I have users, meetings and comments tables and I want users to be able to post comments on users profile and meetings.
I know how to make one to many relationships for users and comments tables, but I want all comments to be saved in one table and show comments on users profile and meetings.
This is my table structure:
users
id
name
comment_id
meetings
id
name
comments
id
user_id
comment
TL;DR The solution is to use polymorphic relationships which Laravel makes really easy.
IMHO I don't think that a many-to-many relationship will do the job. It would mean that:
a user can post multiple comments. Okay
a comment can belong to multiple user. Weird
a meeting can have multiple comments. Okay
a comment can belong to multiple meetings. Weird
Plus you would likely need two comments tables to achieve that. For instance a comment_user table and a comment_meeting.
The kind of relationship that would fit the most your situation is the polymorphic one. The name can be scary because it comes from ancient greek. But the concept behind the name is very simple. And Laravel makes polymorphic relationships very easy. You will certainly recognize your situation in the example given in the Laravel documentation ;)
While saving comment, also keep a field named model (or anyone you like) to identify users profile and meetings
HTH

Php: use data from a join table with mvc

Heya I am novice web dev or actually I am still in education.
I got this situation Where I have 3 tables lets say : Students, Groups and a join table Student_group.
I put my data from Students in the student model and from groups I put its data in the Group Model so I can use it my application. But I store a date in the Student_group table because I need to know when a student changed from a group.
So my question is in which model do I put this date? Do i need to make a new model for the combined tables or do I need to add another attribute to the student model?
Thanks in advance ;D
That depends. Will the student be in many groups, or one?
If one (one to one relationship), you can decide where to put it. The column could be in either the Student table, or the Student_group. In this case, though, it may be advisable to flatten the data and simply add group columns in your Student table. You decide that as well - if it seems unnecessary to have a join for a one to one relationship (usually it is, not always), then flatten it. In either case, the data should stay in its respective model. That said, you should use the Student model if you handle it in the Student table.
If many (one to many relationship), I'd advise putting it in the Student_group table and leaving it in that model as well.
All in all, the model should be a direct reflection of the data it's representing. You could make some methods inside your Student model to make it easier to get the date, for example. However, I'd personally handle that date inside of the proper model, Student_group. As mentioned, the model should be a direct representation of the data. Again, though, there's nothing wrong with making things a bit easier by creating some methods that help out the developer.

laravel 5 OOP structure/architecture advice

I have a general question about how to implement the best practice of model structure for an application I'm building in Laravel 5.
So, at the moment I have things set up like this:
'user' model and table: id, email, password, admin level - this is really just the info for authenticating login.
'user-details' model and table: id, userID (foreign key for user table id field), name, address etc - all the other details
'lesson-type' model and table: id, teacherID (foreign key for user-details table id field), lesson-label etc - info about different types of lessons
At the moment I have a Teacher Controller in which I'm passing through to the view:
- The info from the User table
- The info from the User-details table
- A list of different lesson types for the teacher from the Lesson-type table
But I kind of feel that all this should be tied together with one separate Teacher model which would extend the User-details model (and probably which in turn should extend the User model), but wouldn't have it's own table associated with it, but all the info pertaining to either updates for the User-details or the Lesson-types table would be stored in those relevant tables. Would this be correct?
(I should also say that users may alternatively be parents rather than teachers, and so would I would have a separate Parents model for all the properties and so on associated with parents)
I would then pass only the Teacher model object into the view and thus gain access to all the teacher info such as personal details and array of lesson types.
As I'm typing, this is sounding more and more to me like the right way to go, but it would be great to get some advice.
1 - technical implementation: I guess in the Teacher model, I'd populate all the relevant teacher into class variables (Name, array of lessons etc) in the constructor?
2 - am I over complicating this structure by having both Users AND Users details tables?
3 - Does what I'm proposing make the most structural sense in Laravel?
4 - just another thought I've just had, should the teacherID in the lesson-type table actually refer to the User table rather than the User-detail table... so user-detail and lesson-type would both be direct children of the user table??
Very much obliged for any help :)
You shouldn't extend models like that unless there is a clear inheritance. From a logical standpoint, it just doesn't make any sense since you'll have to overwrite most of what is on the User model anyway. And what you don't overwrite will be incorrectly mapped to the database because they are 2 completely different tables. What you actually want to do is utilize Eloquent relationships.
For clarity, I am assuming this basic structure:
users - id
teachers - id, user_id
user_details - id, user_id
lesson_types - id, teacher_id
Those should be 4 completely different models all interconnected using the Model::belongsTo() method. So the Teacher model would be
class Teacher extends Model {
public $table = 'teachers';
public function user() {
return $this->belongsTo('App\User');
}
}
When you query for a teacher, you can do Teacher::with('user')->get(). That will return all records from the teachers table and on each instance of the Teacher model, you'll be able to call $teacher->user and get the User instance associated with that teacher. That is a full model, not just extra data, so you have access to everything on the User Model, which is generally the main reason for extending
For your list of questions:
I may be misunderstanding you, but this isn't how an ORM works. I'd suggest going back and reading through the Eloquent docs (if you're running 5.0, I suggest reading 5.1's docs since they are much, much better)
It will depend on who you ask, but I tend to think so. If the data is clearly related and there is no reason for it to be shared across record types (for example, I generally have an addresses table that all records reference instead of having 5 address fields repeated on multiple tables), I believe it should all be on one table. It just makes it more difficult to manage later on if you have it in separate tables.
There will be those who disagree and think that smaller scopes for each table are better and it will likely allow for quicker queries on extremely large datasets, but I don't think it's worth the extra trouble in the end
No, as I have explained above
The teacher_id column should reference the teachers table, assuming that lessons belong to teachers and cannot belong to just any user in the system. Using the ORM, you'll be able to do $lesson->teacher->user->userDetails to get that data
I really think you need to go back and read through the Eloquent docs. Your understanding of how Eloquent works and how it is meant to be used seems very basic and you are missing much of the finer details.
Basics
Relationships
Laracasts - Laravel Fundamentals - You would benefit from watching Lesses 7-9, 11, 14, and 21

Difference between HABTM relationship and 2 $belongsTo relationship with a third model

I'm creating a project management system which projects are assigned to users
What's the difference between creating a Model ProjectsUser and defining 2 $belongsTo relationship and defining HABTM relationships in both Project and User models? What would be the most correct way, though? And how do I save the data in the projects_users table?
From my experience, if you want to be able to save or delete rows only from the join table (the one with 2 IDs), then it is much more simple using three models associated through both a hasMany and a belongsTo association.
You can also retrieve data from the join table directly and do the queries you want much more easily
This is what CakePHP documentation says refering to HABTM and saving data:
However, in most cases it’s easier to make a model for the join table and setup hasMany, belongsTo associations as shown in example above instead of using HABTM association.
Here you can find more the full text:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated
I have used this method for a "reads" table (with post_id and user_id) as well as for subscriptions and similar kind of relationships.
The first way is called "hasAndBelongsToMany" [details here].
The second is called "hasMany through" [details here].
The second link relating to "hasMany through" has details and a lengthy explanation about when and why you would want to use it.
Not sure about the specifics of cakephp, but in general defining the relation model explicitly gives you more control over it, for instance if you wanted to do some validation or add callbacks on creation of this relationship.

Categories