Adding data to the model

Hi all.

I am a bit baffled on how to do this.

I have a some models that relate to one main model, Client.

once i have my record i then do a number of calls to various other external sources to get data

and check if model need to be updated

I want to then add this fetched data to the $model variable. the data comes in and is formatted as arrays, but matching the database structure. I don’t want to save the model then load it back in, for various other reasons.

I can get it to work by using:




$model->setAttribute('book_id',"1234567890");



…if the relationship is simple.

but how would i do this for related models with HAS_MANY / BELONGS_TO relationship?

eg. Client can have many Bios.

tried something like this (and loads of other things):




$bio = array('bios'=>array('id'=> '1234567','bio'=> 'Helllooo ladies'));

$model->bios[0]->setAttribute('bio',$bio);



but no luck…

i have also tried




$model->$bios = arrayToObject($bio);



… but also doesn’t work…

any ideas? is there another way to do it?

assuming you have defined the relation bio in Client model -


foreach($bio as $bio){

  $bio->setAttribute('id', '12345');

  $bio->setAttribute('description', 'hello ladies');

}

yea relations are defined.

but this is all happening in the ClientController

so if i try:

foreach($model->$bios as $bio){

$bio->setAttribute(‘id’, ‘12345’);

$bio->setAttribute(‘details’, ‘hello ladies’);

}

i get an "Undefined variable: bios" even though it is part of the model. (i can go echo $model->bios[0]->details; // and this will work)??

replace $model->$bios with $model->bios (second $ not required)

try this




	foreach($model->bios as $bio){

  $bio->setAttribute('id', '12345');

  $bio->setAttribute('details', 'hello ladies');

 }

brilliant you’re a star!!

thanks, much appreciated.

ok, actually i have another question in this regard.

the tables have hundreds of values, which are all matching the database/models exactly. so is there a way of not doing it manually?

eg. there’s a bunch of array values:

bio[‘id’] = 1234567;

bio[‘details’] = “Helllooo ladies”;

bio[‘type’] = ‘group’;

bio[‘city’] = ‘Berlin’;

is there a way of doing it somehow just dumping the whole array into the model - > like such (which doesn’t work):

$model->setAttribute(‘bios’,$bio);

you can directly use


$model->attributes = $bio;