I have 3 tables. 2 of them belong to 1 table.
company:
id
company_info (FK to the id of company_infos)
address (FK to to the id of addresses)
company_info:
id
company_name
owner
address:
id
country
street
number
My relations in the company model:
public function address(){
return $this->hasOne(Address::class, $this->primaryKey, 'address');
}
public function company_info(){
return $this->hasOne(CompanyInfo::class, $this->primaryKey, 'company_info');
}
(My relations do work; I can get the company with their relations in my get request.)
The only way I can think of create a new company is to create company_info and address first and pass their id's to create a new company.
How do I create those 2 models so that the company model gets those 2 models' ids by their relations?
So when I send the data from my front end to Laravel like this to create a new company, how would I make a new company based on this data that's going to fill the other 2 models?
"company_info": {
"company_name": "aCompany",
"owner": "someone"
},
"address": {
"country": "some_country",
"street": "some_street",
"number": 123
}
You would first need to create the company_info and the address data via their models (There is many ways to create a instance of the model this is just the way I prefer, other alternatives include using the new keyword then saving etc.. etc...) like:
$address = Address::create([
// Attributes
]);
// and
$companyInfo = CompanyInfo::create([
// Attributes
]);
which would then have the 2 pieces of data required for creating the Company which can be done the same way as above but set the keys to the respective $address->id and $companyInfo->id
Ex.
Company::create([
// Attributes
]);
If you need any more clarification I am more than willing to elaborate further.
Related
Here's what I want to achieve, we have Staff and every staff can have one Position for a department, as well as one Designation for a department and multiple Additional Charges for multiple departments, one department per Additional Charge. And I want to store all the responsibilities in the staff_responsibilities table
I have a staff table with the following columns
id
name
email
Then I have staff_responsibilities table with the following columns:
staff_id
designation_id
department_id
responsibility_type_id
Responsibility types can be Position and Additional Charge and one staff can have multiple designations with Additional Charge responsibility.
Then I have a responsibility_types table with the following columns:
id
name
// I have no way to tell this relationship to look for a responsibility type 2 (2 is the id of the responsibility called `Designation`)
public function designation()
{
return $this->hasOne(StaffResponsibility::class);
}
// I have no way to tell this relationship to look for a responsibility type 2
public function position()
{
return $this->hasOne(StaffResponsibility::class);
}
// Gives error: Syntax error or access violation: 1066 Not unique table/alias: 'staff_responsibilities'
public function additionalCharges()
{
return $this->belongsToMany(StaffResponsibility::class, 'staff_responsibilities','designation_id');
}
Any help would really be appreciated.
staff_responsibilities table
responsibility_types table
designations table
Here's what I want to achieve, we have Staff and every staff can have one Position for a department, as well as one Designation for a department and multiple Additional Charges for multiple departments, one department per Additional Charge.
It sounds to me like it would be beneficial to create a model for Position, Designation and Additional Charges. It feels like you may need to normalize your database or to change staff_responsibilities as a pivot table.
But hard to say without knowing your application.
To answer your question, you could add some scopes in StaffResponsibility
class StaffResponsibility extends Model{
public function scopeDesignation($query)
{
return $query->where('responsibility_type_id','=',2);
}
}
and use it
public function designation()
{
return $this->hasOne(StaffResponsibility::class)->designation();
}
And the last one is a hasMany relation and not a manyToMany according to what you wrote:
public function additionalCharges()
{
return $this->belongsTo(StaffResponsibility::class, 'staff_responsibilities','designation_id')->additionalCharges();
}
I have one user table named "Users".
There are different roles (trainer and client).
I want to make like Trainer can have many clients, but client can have one trainer.
I made table in db like "ClientTrainer" where is stored only ID of users with columns
"id, client_id, trainer_id"
and I am trying to return something like this:
$user->allclients(); - return all clients (logged as trainer)
$user->owntrainer(); - return his trainer (logged as client)
Its fresh laravel 5.7 with only Auth and Roles.
I am sure it can only be done with modals, but i need a little help.
Thanks.
First, create a model for table ClientTrainer as well. Then try this inside your Users model:
public function clients()
{
return $this->belongsToMany(
"UsersModelNamespace",
"IntermediaryTableModelNamespace",
"trainer_id",
"client_id",
"id",
"id"
);
}
public function trainer() // will return a collection with one element
{
return $this->belongsToMany(
"UsersModelNamespace",
"IntermediaryTableModelNamespace",
"client_id",
"trainer_id",
"id",
"id"
);
}
Why I'm posting belongsToMany when retrieving the trainer? Laravel 5.7 does not support hasOneThrough() relationship.
The best thing you can do is to separate your Table into two; "users" & "trainers".
Even if they have exactly the same fields, they dont have the same functionality, so that justifies the separation. Then just add trainer_id in your table "users"
I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.
I'm using octobercms which uses eloquent models.
I have several tables (Books, Movies, Comics...) and I need to link them to an agegroup table. Every book (movie, comic) gets exactly one agegroup.
My first intention was this:
table agegroup:
id
...
table book:
id
agegroup_id
...
table movie:
id
agegroup_id
...
But I dont get how to put that into an Eloquent model.
Bonus question: there are other similar links (every book, movie etc. has exactly one section) where I need basically the same fields as in the agegroup table: should I reuse that (how?) or create another similar table?
Relationships don't have a single direction, they're two-ways, so one-to-many is the same as many-to-one, only the perspective changes. Meaning that from one perspective a model has many others, and from the other a model belongs to another model. Even the naming used in defining the relationships is very intuitive: hasMany and belongsTo. So here's how you would configure the relationship between a Book model and a AgeGroup model.
A book belongs to only one age group:
class Book extends Model
{
public $belongsTo = [
'ageGroup' => 'Acme\Blog\Models\AgeGroup'
];
}
Then you can get the age group of a book like this:
Book::find(1)->ageGroup->name; // I'm assuming age groups have names
The revers of that relationship is that an age group can have many books associated to it:
class AgeGroup extends Model
{
public $hasMany = [
'books' => 'Acme\Blog\Models\Book'
];
}
Then you can get all books that belong to an age group like so:
foreach (AgeGroup::find(1)->books as $book) {
// access book details like: $book->title;
}
The same logic applies to movies and whatever other entities that can have one age group.
I have a users table and consultant_profile table set up on my db. They are related and in my controller action i can see in the users object(from a model) that it has a relations array and in there is the profile object.
I am now trying to create a table for qualifications which has a one to many relationship with the consultants profile so one profile can have many qualifications.
For ease i here is a shorter version of the schema for the tables:
consultant_profile [
- id
- address line 1
- postcode
]
consultant_qualifications [
- id
- consultant_profile_id
- qualification
]
I have put this in my model for the consultant_profile
public function qualifications()
{
return $this->hasMany('ConsultantQualifications', 'consultant_profile_id');
}
and this in my consultant_qualifications model
public function profile()
{
return $this->belongsTo('ConsultantProfile',null,"consultant_profile_id");
}
I have tried it with putting in foreign/local keys and without.
What i expect the out come to be is i can look in the relations array of user object and see the profile object, i could then look into profile object and in its relations array i should see qualifications object
But i don't, any reason why?