2015-11-25 97 views
2

我有一個包含日期和註釋的採購表以及purchaseId作爲採購表的外鍵的purchasedetail表。在這兩個模型表之間的關係是:Laravel 5一對多關係主數據和父數據CRUD

採購模式: -

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

我得到這個錯誤的回報:

ErrorException在helpers.php線703的preg_replace():參數 不匹配,pattern是一個字符串,而替換是一個數組。那 意味着$ purchase-> save()不可能。這裏我從Input :: get('Purchasedetail')獲得一個數組列表 。

那麼我現在可以做什麼?

回答

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); 
} 
+0

那麼它只能存儲一個數據辛格運河和所有其他數據定義null作爲項目Id是在分貝空,它應該是1。我需要插入列表數據。在Input :: get('Purchasedetail')中,它實際上得到的不是一行數據的數組列表。 –

+0

我編輯了我的答案。 – kotapeter

+0

您的代碼很好,但只有Id和Purchase_Id插入purchasedetails表中。其他數據呢?例如我有ItemId,Quantity,詳細信息表。我使用的代碼如下所示:foreach(Input :: get('Purchasedetail')as $ purchasedetails){ \t $ purchasedetail = new Purchasedetail(); \t $ purchasedetail-> ItemId = $ purchasedetails-> ItemId; \t $ purchasedetail-> GradeId = $ purchasedetails-> GradeId; \t $ purchasedetail-> Quantity = $ purchasedetails-> Quantity; \t $ purchase-> purchasedetails() - > save($ purchasedetail); } .....但現在沒有數據插入。你能解答爲什麼嗎? –

0

我現在確定,但你可以這樣。

$purchase = new Purchase(); 
... 
$purchaseDetails = new PurchaseDetails(); 
$purchaseDetails->purchaseId = $purchase->id; 
$purchaseDetails->save();