Hardist
Hardist

Reputation: 1993

Laravel push a one-to-one relation

I have a one-to-one relation for my products and their corresponding prices. What I would like to do, is when I create a new product, the new product is stored in the "products" table, but that also the price is saved in the "prices" table, including the "products_id". Here is what I have now:

Products Model:

class Products extends Eloquent {

    public function prices()
    {
        return $this->hasOne('Prices');
    } 
}

Prices Model:

class Prices extends Eloquent {

    public function products()
    {
        return $this->belongsTo('Products');
    }
}

Controller Store Method:

$product = new Products;
$product->name = Input::get('name');

$product->prices->price = Input::get('price');

$product->push();

I am getting an error though:

Indirect modification of overloaded property Products::$prices has no effect

dd of my $product:

object(Products)#606 (20) {
    ["fillable":protected]=> array(3) {
       [0]=> string(4) "name"
       [1]=> string(8) "selected"
       [2]=> string(6) "number"
    }
    ["connection":protected]=> NULL 
    ["table":protected]=> NULL
    ["primaryKey":protected]=> string(2) "id"
    ["perPage":protected]=> int(15)
    ["incrementing"]=> bool(true)
    ["timestamps"]=> bool(true) 
    ["attributes":protected]=> array(0) { }
    ["original":protected]=> array(0) { } 
    ["relations":protected]=> array(0) { }
    ["hidden":protected]=> array(0) { } 
    ["visible":protected]=> array(0) { } 
    ["appends":protected]=> array(0) { }
    ["guarded":protected]=> array(1) {
       [0]=> string(1) "*"
    }
    ["dates":protected]=> array(0) { }
    ["touches":protected]=> array(0) { }
    ["observables":protected]=> array(0) { }
    ["with":protected]=> array(0) { }
    ["morphClass":protected]=> NULL
    ["exists"]=> bool(false)
}

Upvotes: 1

Views: 331

Answers (2)

Mustafa ASAN
Mustafa ASAN

Reputation: 3825

Push is can be used when updating data and its relations but you have to first save product then save price when creating first time.

    $product = new Products();
    $product->name = 'pro2';
    $product->save();

    $price=new Prices();
    $price->price=3;


    $product->prices()->save($price);

Also you should use transaction for data to be in consistent state.

Upvotes: 1

Hardist
Hardist

Reputation: 1993

Fixed it now using the right naming conventions and with this code:

        $product        = new Product;
        $product->name      = Input::get('product');
        $product->category_id   = Input::get('category');
        $product->save();

        $price          = new Price;
        $price->price       = Input::get('price');
        $price->save();

        $product->price()->save($price);

Answer found here:

laravel: eloquent example insert data to database

Upvotes: 0

Related Questions