【问题标题】:Laravel push a one-to-one relationLaravel 推送一对一关系
【发布时间】:2015-08-11 07:56:55
【问题描述】:

我的产品及其相应的价格是一对一的关系。我想做的是,当我创建一个新产品时,新产品存储在“products”表中,但价格也保存在“prices”表中,包括“products_id”。这是我现在拥有的:

产品型号:

class Products extends Eloquent {

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

价格模型:

class Prices extends Eloquent {

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

控制器存储方法:

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

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

$product->push();

我收到一个错误:

间接修改重载属性 Products::$prices 无效

我的 $product 的 dd:

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)
}

【问题讨论】:

  • 你能告诉我你的 $product 的 dd 吗?
  • 添加到我的答案中,因为评论太长了:)
  • 对不起先生。请使用此代码: $product = Products::all();然后使用 print_r($products)。并显示数据的 tnx。
  • $product->prices->price = Input::get('price'); 是否创建新的价格模型并将其保存到数据库中?检查你的数据库是否真的创建了。
  • 可能是命名问题吗? Eloquent 期望你的模型类名是单数的。所以Price而不是Prices,和Product而不是Products,而数据库表应该是复数。

标签: laravel laravel-4 push relation


【解决方案1】:

更新数据及其关系时可以使用推送,但您必须先保存产品,然后在第一次创建时保存价格。

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

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


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

您还应该使用事务来使数据处于一致状态。

【讨论】:

  • 你可以使用$product->price()->associate($price);,然后在最后做一个$product->save()
  • 是的,它也可以代替 new Product() ,Product::create 可用于删除保存语句
【解决方案2】:

现在使用正确的命名约定和以下代码修复它:

        $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);

在这里找到答案:

laravel: eloquent example insert data to database

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2014-08-22
    • 2018-10-03
    • 1970-01-01
    • 2018-05-29
    • 2013-10-21
    • 2014-06-24
    • 2018-04-20
    相关资源
    最近更新 更多