We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



5.7k
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 = 'https://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 = 'https://your-host.com/path/to/video.ext'

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

$product->save();

Both of those should work