Model doesn't show up on relationship right after saving? - laravel

For example
$user->transactions()->save($transaction);
dump($transaction->id); // id: 4
dd($user->transactions); // last id is 3
The $transaction that is saved does not show up in $user->transactions. This is a polymorphic relationship.

When you save a model through a relationship, all Laravel does is set the appropriate foreign keys. It doesn't set the newly saved model to the relation or add it to a collection.
If you want the model with updated relations use the fresh function.
$user->transactions()->save($transaction);
$user = $user->fresh('transactions');
Edit answer updated following #JCLee's correction to assign the result of $user->fresh().

Related

Delete one entry from pivot table laravel

How can i delete only one entry from many-to-many relationship pivot table in laravel if i have the id of the row?
Solved it. I used:
->wherePivot('id', '=', $pivot_id)->detach()
and it worked great.
Suppose you have User & Entity models with many-to-many relationship. Then you could use
$user->entity()->detach($entityId);
That will only delete the row with that $entityId
The best practice you can do it like this,
// Detach a single entity from the user...
$entity = Entity::find($your_entity_id);
$user->entities()->detach($entity->id);
First, find the entity with your desired id by Entity Model,
$entity = Entity::find($your_entity_id);
After you will get entity, you can pass it into detach() method,
$user->entities()->detach($entity->id);
For more information go through this link.

How can I get a list of filtered values from a many2many field in odoo 11?

I have a model named "student" that had a many2many relation with a model named "authorized" and another model named "authorized" with a many2many relation with the model "student". In the other hand, I have a third model named "exit_control" that contains a many2one relation with the model "student".
I wanna a second field many2one in the model "exit_control" that shows only the authorizeds related with the student selected.
In other words: if student1 is related with authorized6 and authorized8, and the complete table of authorized had 20 authorizeds, and I select the student1 in the field student_id of the model exit_control, I wanna show a field many2one with the authorized6 and authorized8.
Student model had:
authorized_ids = fields.Many2many('aula10.authorized', string='Authorizeds')
Authorized model had:
authorized_for_ids = fields.Many2many('aula10.student', string='Can get this student:')
Exit_control model had:
student_id = fields.Many2one('aula10.student',string='Student')
Given_to_id = fields.Many2one('aula10.authorized', string='Given to:')
Given_to_id is the field that I wanna use for show the filtered authorizeds.
I tried to use the attribute domain in view and in model, but was impossible for me.
Can you help me, please?
In model definition?
Given_to_id = fields.Many2one('aula10.authorized', string='Given to:', domain=[('authorized_for_ids', 'in', [student_id ])])
eventaully you can use computed field with store option?

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.

Updating a pivot table in Eloquent

I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.

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