【发布时间】: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