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

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;

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.

how to get data from a pivot table in a query at a controller

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

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();

Laravel how many relationship can be chained

I have a database composed by users, users_child, child.
I create a ONE to MANY relationship between Users and users_child, then i create a relationship between users_child and child. Now the below code work:
$test = users::find(1)->users_child
$test1= users_child::find(1)->child
Now i want to know if is possible to create a single row that link the three table like this:
$test = users::find(1)->users_child->child
I create the relationship in the model but in the db i don't create Foreign Key, it's a problem? on the model i specify the field for link table.
http://laravel.com/docs/5.1/eloquent-relationships#querying-relations
You can chain relationships like this:
$user = Users::with("users_child.child")->where("id",1)->first();
Each point will mean a relation stored in the first.
Out of users users_child will be taken and out of users_child child will be taken. (Relations)
foreach($user->users_child as $user_child) {
$user_child->child;
}
will get you the data you need.

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