How can I save related record automaticaly?

I have a JSON response from api with the structure:

{
    Product: {
        id: "3",
        Video: [
            {
                id: "1",
                url: "c",
            },
            {
                url: "d",
            },
        ]
    }
}

In my Product model, I set Video model as related:

  ...
  initialize(){
      $this->hasMany("id","Video","product_id")
  }
  ...

Is possible to save/create these related objects automaticaly?



4.3k
edited May '15

Here are a few simplified examples:

/**
 * Create a product and add a video to it in one transaction
 **/
$video = new Video();
$video->url = 'http://your-host.com/path/to/video.ext'

$product = new Product();
$product->video = $video;

$product->save();
/**
 * Add a video to a pre-existing product
 **/
$video = new Video();
$video->url = 'http://your-host.com/path/to/video.ext'

$product = Product::findFirstById($product_id);
$product->video = $video;

$product->save();

Both of those should work