I have a purchase table with date and comments and a purchasedetail table with purchaseId as a foreign key of purchase table. Have the relation in both model table is :
Purchase model:-
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model {
public function purchasedetails() {
return $this->hasMany('App\Models\Purchasedetail', 'PurchaseId', 'Id');
}
}
and the
Purchasedetail model :-
use Illuminate\Database\Eloquent\Model;
class Purchasedetail extends Model {
public function purchase() {
return $this->belongsTo('App\Models\Purchase', 'PurchaseId', 'Id');
}
}
How can I create, update and delete both table data with relations? My main problem is when I send data to controller and try to create, master page data is created but it can not create parent table data or update it. I am using Laravel 5.
Some code of my controller:
$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);
I get this error in return:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array. That means $purchase->save() can not possible. Here i get an array list from Input::get('Purchasedetail').
So what can I do now?
Try the following:
$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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments