Laravel Many to many relationship with custom key relation - laravel

Before you mark this question as duplicate, please see the details :) I have a problem related to many to many relationship with custom columns linking
I have following tables
Employees
-Id
-brink_id <----- This is third party id I am saving of employee
-name
Jobs
-id
-brink_id <----- This is third party id I am saving of job
-description
employee_job
-id
-brink_id <----- This is third party id I am saving of relationship for third party
-brink_employee_id
-brink_job_id
In Employee Model I have created relationship
public function jobs()
{
return $this->belongsToMany('App\Models\Job','employee_job','brink_employee_id','brink_job_id');
}
And in Jobs Model
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function employees()
{
return $this->belongsToMany('App\Models\Employee','employee_job','brink_job_id','brink_employee_id');
}
Actually I want to have many to many relationship with brink_id in employees table and brink_id in jobs table presented as brink_employee_id, brink_job_id in employee_job table not with ID (primary columns of respective table).
But when I try to insert in pivot table using following, it always inserts employee ID rather than brink_id
$employee = Employee::with('jobs')->where('brink_id',$employeeJob['brink_employee_id'])->first();
$employee->jobs()->attach($employeeJob['brink_job_id'], ['is_active' => 1]);
For example if brink_id in employee table is 123456 and ID is 1, the above code in employee_table will store 1 in employee_brink_id rather than 123456.
Please let me know what I am doing wrong.

If you don't specify a different parent key and related key, it will default to your current model's primary key and the related model's primary key respectively.
Specify the parent key name as the 5th argument and the related key name as the 6th argument:
return $this->belongsToMany('App\Models\Employee', 'employee_job', 'brink_job_id', 'brink_employee_id', 'brink_id', 'brink_id');
However, I'd personally use the ids from your system and not the ids from a 3rd party system in your relationships.

Related

How to use an array as a foreign key in a model and build a hasMany relationship in laravel

This is my schema as follows:
Medicines
id
price
description
etc..
Ecommerce Orders(has many Medicines)
id
user_id
products (array that holds the id's of the medicine's and quantity)
And in my EcommerceOrders Model i have
protected $casts = [
'products' => 'array',
];
public function items()
{
return $this->hasMany(Medicines::class,'id','products')->withTrashed();
}
What I'm trying to do is to create a relationship between ecommerceOrders and medicines so when i get the data of an order that a client has made i also get the data of the products he has orederd
How can i do this with the foreign key in this instance being an array
You need another table called a pivot table, "ecommerce_order_medicines" with the fields medicine_id, ecommerce_order_id, qty
You would have a record for each different medicine that belongs to the ecommerce order.
You should not store it the way you are doing right now, you won't be able to make any relationship with it stored as an array like that. You also are making it much more difficult to do any kind of reports in the future, because you won't be able to properly query your database when it's stored as an array with ID's and QTY in the same column with no relationship. You will likely have to process large sets of data through PHP instead which won't scale very well.

Retrieve values from related table foreign key using Eloquent

Sorry if the question isn't clear.. I'm not super fluent in databases.
I have three tables:
companies equipment parts
----------- ----------- -----------
id id id
name company_id equipment_id
Using Eloquent, how do I get a Collection of all the parts that belong to the company with id=1
I know you setup relationships in the model. So now I can get all a company's equipment ($myCompany->equipment), and all equipment's parts ($myEquipment->parts), but I'm not sure how to easily get values in the reverse direction two tables away.
Thanks!
Laravel has such a beautiful documentation and API for this very thing. Take a look at the hasManyThrough relationship.
So in your Company model add this:
/**
* Get all of the parts for the company.
*/
public function parts()
{
return $this->hasManyThrough('App\Part', 'App\Equipment');
}

Laravel/Eloquent get all appointments from a polymorphic "member_id" through a appointment_members table

I have an appointments table and an appointment_members table and my users need to be able to get a collection of appointments by searching with a "member_id", which could be a Person, Incident or CustomerID. The appointment_members table has member_id and appointment_id columns, so the member_type (also a column) is irrelevant. This all set up by a previous dev and what is missing are the relationships on the Eloquent models. I'm just creating a simple GET route that needs to return any/all appointments by that member_id. Each row has one appointment, so if I were to pass in a member_id that returned 10 results, some could have appts and others not, but at the end of the day I just need a collection of appts that are related to that member_id. Here's a screenshot of the appointment_members table:
If I create a simple hasOne relationship to appointments on appointment_members:
public function appointments()
{
return $this->HasOne(Appointment::class, 'id', 'appointment_id');
}
I can get a collection of appointment_members with it's respective appointment, but not sure how I boil it down to just getting the appointments. One workaround I have is to use that HasOne and then pluck/filter the appointments:
$appointmentMembers = AppointmentMembers::where('member_id', $request->input('memberId'))->get();
$appointments = $appointmentMembers->pluck('appointments')->filter();
Curious if anyone might see a better way to go about this. Thanks!
I'm possibly not understanding, but I would probably take the simplest approach here if the member type is not important.
The table is already set up to handle either a belongsToMany or a morphMany, so create the relationship on the Member class (or if you don't have a parent member class, stick it on each of the types Person, Incident, etc. You can also do this via poly, of course, but this is a simple example to get what you need):
public function appointments()
{
return $this->belongsToMany(Appointment::class)->withPivot('member_type');
}
And then just query on the member object you need appointments for (having poly would make this one step):
$allAppointmentsForID = $member->appointments();
$appointments = $allAppointmentsForID->wherePivot('member_type', $whateverClassThisIS);
The above takes member_type into account. If this doesn't matter, you can just use the top line.
Your original db is setup to handle polymorphic relations, so if you wanted more than the appointment you can set it up this way as well. For now, you'll need to add the TYPE to the query to cover the different classes.
If the member type is important, polymorphic might be something like this on the Member class:
public function appointments()
{
return $this->morphMany(Appointment::class, 'memberableOrmember_typeOrWhatever');
}
Then you can query on the member object with just one line
$appointments = $member->appointments();

Get back data from the pivot table when store a many-to-many relationship

I have a many-to-many relationship between projects and surveys. I can successfully create a relationship between a survey and a project with
$userSurvey = $project->surveys()->save($survey);.
This will create a new record inside the question_survey pivot table (The pivot table contains the columns id, question_id and survey_id.)
$userSurvey will receive the newly created survey model. Is there any way to receive also the id of the new record in the question_survey pivot table?
When retrieving many to many relationships, Laravel will automatically attach the pivot to the resulting Model, so in your case, $userSurvey will automatically have an attribute called pivot that holds, well, of course, the pivot.
But by default, that pivot attribute only holds the foreign keys, so in your case, the question_id and survey_id. If you have any other extra attributes,(in your case id), simply use the withPivot method, as follows.
public function surveys()
{
return $this->belongsToMany('App\Question', 'question_survey')
->withPivot('id');
}
Now you can access the id from the pivot table:
$userSurvey->pivot->id;
Bonus, if you think that the pivot word just does not fit your wording style, just use the as method in your relationship to customize the variable name of the pivot attribute.
public function surveys()
{
return $this->belongsToMany('App\Question', 'question_survey')
->as('question_survey')
->withPivot('id');
}
Now you can access the id from the pivot table:
$userSurvey->question_survey->id;

Mapping relationships to generic models in Datamapper for Codeigniter

I have a number of different models in a system backed by the Datamapper library for Codeigniter such as Posts and Pages and am interested in adding Likes and Comments to the system. The way I see it, Likes and Comments can apply to any sort of model that extends Datamapper. How would I go about defining such a relationship (keep Likes for any sort of model in the same table, as well as Comments)?
I tend to create separate tables for likes and comments. I usually create this sort of schema:
Likes
-----
id // autoincrement
obj // the related model (the name of the model that is being liked)
obj_id // the foreign key
user_id // the user id that liked the model object
created // timestamp
updated // timestamp
Then the comments table:
Comments
--------
id // autoincrement
obj // the related model (same as above)
obj_id // the foreign key
message // the comment itself
user_id // the user id that commented on the model object
created // timestamp
updated // timestamp

Resources