我有一张包含日期和评论的购买表,以及一张purchaseItail表,其中purchaseId作为购买表的外键。两个模型表中的关系是:
购买模式: -
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model {
public function purchasedetails() {
return $this->hasMany('App\Models\Purchasedetail', 'PurchaseId', 'Id');
}
}
和 Purchasedetail型号: -
use Illuminate\Database\Eloquent\Model;
class Purchasedetail extends Model {
public function purchase() {
return $this->belongsTo('App\Models\Purchase', 'PurchaseId', 'Id');
}
}
如何创建,更新和删除具有关系的表数据? 我的主要问题是当我向控制器发送数据并尝试创建时,创建了主页数据,但它无法创建父表数据或更新它。 我正在使用Laravel 5。
我的控制器的一些代码:
$purchase = new Purchase();
$purchase->Date = Input::get('Date');
$purchase->Comment = Input::get('Comment');
$purchase->purchasedetails = Input::get('Purchasedetail');
$purchase-> save();
if (count($purchase->purchasedetails) != 0) {
foreach ($purchase->purchasedetails as $v) {
$purchasedetail = new Purchasedetail();
$purchasedetail->ItemId = $v->ItemId;
return $v->ItemId;
}
}
$purchase-> Purchasedetail()->save($purchasedetail);
我得到了这个错误:
helpers.php第703行中的ErrorException:preg_replace():参数 不匹配,pattern是一个字符串,而replacement是一个数组。那 意味着$ purchase-> save()是不可能的。在这里,我得到一个数组列表 来自Input :: get('Purchasedetail')。
那我现在该怎么办?
答案 0 :(得分:1)
尝试以下方法:
$purchase = new Purchase();
$purchase->Date = Input::get('Date');
$purchase->Comment = Input::get('Comment');
$purchase-> save();
$purchase->purchasedetails = Input::get('Purchasedetail');
foreach ($purchase->purchasedetails as $row) {
$purchasedetail = new Purchasedetail();
$purchasedetail->ItemId = $row['ItemId'];
$purchasedetail->GradeId = $row['GradeId'];
$purchasedetail->Quantity = $row['Quantity'];
$purchase->purchasedetails()->save($purchasedetail);
}
答案 1 :(得分:0)
我现在肯定,但你可以这样做。
$purchase = new Purchase();
...
$purchaseDetails = new PurchaseDetails();
$purchaseDetails->purchaseId = $purchase->id;
$purchaseDetails->save();