I have a massive edit page and the values are taken from 4 tables. I have them all in a object and sorted which ones go where. Although when I call my main model, can I update its relationship by passing in the object or array?
Main Model
$officiant = Officiant::find($id);
Its relationship is the "detail" and "profile"
Example:
$officiant->fname = $request->fname;
$officiant->lname = $request->lname;
$officiant->phone = $request->phone;
$profile = new \StdClass();
$profile->gender = $request->gender;
$profile->profile = $request->profile;
$detail = new \StdClass();
$detail->street = $request->street;
$detail->city = $request->city;
I can update officiant by passing it like this
$officiant->update(array ($officiant));
Although, can I update the detail one by doing something similar, as in
$officiant->detail->update(array ($detail));
$officiant->profileupdate(array ($profile));
If you are updating via a relation ship it should be
$officiant->detail()->update(array ($detail));
Using ->detail() instead of ->detail sends a query builder instance that can be chained with update().
Related
I updated my notes table with 4 new columns: classification, pod, sampled, followup.
I would update my model like so (which still works like this):
$note->account_id = $account->id;
$note->name = $request->input('account-note-title');
$note->description = $request->input('account-note-description');
$note->save();
But if I try and post to the new columns it fails.
$note->account_id = $account->id;
$note->name = $request->input('account-note-title');
$note->description = $request->input('account-note-description');
$note->classification = $request->input('account-note-classification');
$note->pod = $request->input('account-note-pod');
$note->sampled = $request->input('account-note-samplebrand');
$note->followup = $request->input('account-note-followup-date');
$note->save();
Do I have to refresh the model or anything?
You can create new value using laravel Create methode like below
ModelName::create($request->all())
In this case you have to put your all input field in the $fillable variable of MODEL.
You can update item using the following method
$model = findOrFail($id)
$model->update($request->all())
I have a problem with phalcon model magic getter and setter.
I want to update like this tutorial :
https://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records
But the thing is my proj is multi module and separated models folder.
So I have to use alias for hasOne and belongsTo
$this->hasOne('user_id', '\Models\UserProfile', 'user_id', array('alias' => 'UserProfile'));
and
$this->belongsTo('user_id', '\Models\CoreUser', 'user_id', array('alias' => 'CoreUser'));
What i want to do is like this.
$CoreUser = new CoreUser();
$user = $CoreUser->findFirst(array(
//...condition here to find the row i want to update
));
$user->assign($newUserData);
$user->setUserProfile($newProfileData);
$user->update();
But above this code only save user data and don't save Profile data at all. (have profile data -- confirmed)
So do you have any idea what the error is? if u know, Please help me or give me a tip.
I got it now.. when assigning like $user->UserProfile = $newUserProfile;
$newUserProfile should b a Model Object.
So my new code is
$CoreUser = new CoreUser();
$user = $CoreUser->findFirst(array(
//...condition here to find the row i want to update
));
$profile = $user->UserProfile; //$profile is now model object which related to $user
//assign new array data
$profile->assign($newProfileData);
$user->assign($newUserData);
/*
* can also assign one by one like
* $user->first_name = $newProfileData['first_name'];
* but cannot be like $profile = $newProfileData or $user->UserProfile = $newProfile
* since it's gonna override it the model with array
*/
$user->UserProfile = $profile;
$user->update(); // it's working now
Thanks to #Timothy for the tips too .. :)
Instead of doing
$profile = $user->UserProfile;
You should instantiate a new UserProfile object
// find your existing user and assign updated data
$user = CoreUser::findFirst(array('your-conditions'));
$user->assign($newUserData);
// instantiate a new profile and assign its data
$profile = new UserProfile();
$profile->assign($newProfileData);
// assign profile object to your user
$user->UserProfile = $profile;
// update and create your two objects
$user->save();
Note that this will always create a new UserProfile. If you want to use the same code to update and create a UserProfile, you can maybe do something like:
// ...
// instantiate a (new) profile and assign its data
$profile = UserProfile::findFirstByUserId($user->getUserId());
if (!$profile) {
$profile = new UserProfile();
}
$profile->assign($newProfileData);
// ...
User hasmany profiles
Profile belongs to user.
Following works:
$u = User::firstOrNew(['email' => $s['email']]);
$u->name = $s['name'];
$u->avatar = $s['avatar'];
$u->save();
$p = new UserProfile;
$p->provider = $s['provider'];
$p->provider_uid = $s['provider_uid'];
if ($u->profiles()->save($p)) {
}
But I don't really like it, is there a better more streamlined way? Why can't I save in 1 atomic insert?
You are trying to save data to 2 different table, that's why you can't do this using a single insert.
The way you do it - first save the parent object, then associate the child object and save that - is how it is usually done.
You could also have a look at the push() method of Eloquent's models, that works in a similar fashion as save() but also calls save() on related models. Using this method allows to replace this code:
$a = new A;
$a->save();
$b = new B;
$b->a()->associate($a);
$b->save();
with
$a = new A;
$b = new B;
$b->a()->associate($a);
$a->push();
I have a AR model that I am trying to duplicated but just need to manually change the foreign key.
$_POST['competition_id'] = 99;
$prizes = CompetitionPrizes::model()->findAll('competition_id =:competition_id',array(':competition_id'=> $_POST['competition_id']));
This query basically queries the prizes table and gets all the rows for a particular competition. With the prizes object I would like to basically re-insert/duplicate the same information except the competition id which I want to manually set.
I did something similar for an AR object that basically only has one row and that worked well, however in this instance as a competition can have more than one prize this same code won't.
// My existing code for duplication process
$obj = Competitions::model()->find('competition_id=:competition_id', array(':competition_id' => $post['competition_id']));
$clone = clone $obj;
$clone->isNewRecord = true;
unset($clone->competition_id); // i want to remove this so it is auto inserted instead via the db
$clone->save();
This works great - how would I modify this on a 'collection' of prizes and have this duplicated into the database while setting my own 'competition_id' value.
Note - i'm to new to Yii, so please let me know if I have made any obvious errors/bad practice
Cloning won't work. You need to assign the attributes to a new object:
$obj = Competitions::model()->find('competition_id=:competition_id', array(':competition_id' => $post['competition_id']));
$clone = new Competitions;
$clone->attributes = $obj->attributes;
$clone->save();
If a more generic way of duplicating a Model / ActiveRecord in Yii2 Framework is required, you might use this solution:
$copy = clone $model;
$copy->isNewRecord = true;
foreach ($model->getPrimaryKey(true) as $field => $value) {
unset($copy->{$field});
}
$copy->save();
GitHub issue discussion about duplicate models: https://github.com/yiisoft/yii2/issues/7544#issuecomment-77158479
The answer for my problem although Michiel above helped me out - alternatively if you wouldn't mind adding another answer i'll give you the accepted answer.
foreach($models as $model)
{
$clone = new Competitions;
$clone->attributes = $model->attributes;
$clone->competition_id = '123' // custom var i am setting manually.
$clone->save();
}
How about (yii2 syntax):
$model=Competitions::findOne([':competition_id' => $post['competition_id']]);
$model->id = null;
$model->isNewRecord = true;
$model->save();
I have two models Property and Amenity the relationship between them is many to many. the reference class is PropertyAmenity when i want to insert single record into one model it is easy for me.
to insert into Property
$property = new Property();
$property->serial = 'SER09088';
$property->title = 'Some title';
$property->save();
and to insert record into Amenity it is
$amenity = new Amenity();
$amenity->name = 'Swimming Pool';
$amenity->save();
what i want to do is add existing amenities to Property the record of which holds in reference class PropertyAmenity for example something like.
$property = new Property();
$property->serial = 'SER09088';
$property->title = 'Some title';
$property->PropertyAmenity->amenity_id[] = 1;
$property->save();
when i try the above code it gives me following exception
Add is not supported for PropertyAmenity
the situation is i gather collective information from a form, from a user. for example a user inputs all the value related to Property and select existing Multiple Amenities from the form and submit. i need to save Property in property table and the selected amenities in property_amenity table which consist of two columns property_id and amenity_id, how do insert this value in doctrine?
After digging around a little bit, i found the solution myself and as expected, it is so easy to implement. the only change i had to do was.
From this
$property->PropertyAmenity->amenity_id[] = 1;
To
$property->PropertyAmenity[]->amenity_id = 1;
$property->PropertyAmenity[]->amenity_id = 3;
$property->PropertyAmenity[]->amenity_id = 5;
and it works, hope it helps someone :)