I have three models.
PERSON (hasOne(EMPLOYEE), hasMany(CHILDREN))
id,
name
EMPLOYEE
id,
person_id
CHILDREN
id,
person_id
I want to add a child to person model but i have access to EMPLOYEE_ID. I tried to code but it doesn't work.
$employee->person()->children()->save($child);
and
$employee->person()->children()->associate($child);
But both doesn't work. I don't know if this can be accomplished by just one line of code.
Try this way, When you are calling person() it will return the relation instead of the object itself.
$employee->person->children()->save($child);
Related
I am currently trying to create a new record using GORM and these two models has a one to one relationship with each other. Model1 has 'has one' relationship with Model2. I was thinking if it is possible to create query Model2 instead of Model1 in this case. Here is an example from the docs:
So in the docs context, is it possible to create query from the CreditCard struct as I want to persist the 'has one' relationship.
I managed to solve it! You can simply just include the foreign key in the struct model when creating it. For example:
CreditCard{
Number: "41111111111111"
UserID: <include the id here> // make sure the credit card gorm model has UserID foreign key specified
}
db.Create(&CreditCard)
I have created a query in function at the controller where I want to get data from a pivot table based on the value sent using jquery.how can i create a function to get the values of the id associated with the selected house id in the controller.i have tried this but i get an error
$rentalcategoryhouses=Rental_house::whereIn('rentalcat_id',$rentalcategorydetails['catids'])
->with('housetags')->where('tag_id',$data['rentaltag'])->get();
the housetags here is the belongstoMany function in the house model that associates the houses with the tags.
function housetags(){
return $this->belongsToMany(Rental_tags::class,'rentalhouse_tags','rental_id','tag_id');
}
i want to get all the houses associated with the specific tag_id using a query in the controller.
this answer here solved my bug solution
Maybe simple, but I can't figure it out...
When I create a record using Eloquent and a model that extends Model, and then get its id right after it just works:
$example = Example::create(['name'=> 'exie']);
dd($example->id);
// returns id (ex. 15) as expected from the created record...
When I create a record using a model that extends Pivot and try to get id, it only returns null.
$customPivotExample = CustomPivot::create(['name' => 'custie']);
dd($customPivotExample->id);
// returns null instead of id...
The records all have a PK so I expected to just get the ID back, but apparently there is something about using a custom pivot model and getting it's id after creation what I am overlooking..
(examples are really simple but the actual code only contains more key=>value pairs and nothing more)
anyone has any idea?
Own Answer
Putting this here because this is not written (somewhat) in the Laravel documentation.
They mention this about auto incrementing ID's:
https://laravel.com/docs/9.x/eloquent-relationships#custom-pivot-models-and-incrementing-ids
I had not done this (my bad), but doing this also enables getting the ID after creation of a pivot record as in my second example....
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();
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;