简体   繁体   中英

Laravel 4.2 & AngularJS Insert data into multiple tables where PK in Table_1 is FK in Table_2 & Table_3

I am very new to Laravel and currently trying to learn how it works. I work with a project where we use Laravel and AngularJS. I am currently trying to insert data into 3 different tables from one from in AngularJS, i can get the values just fine but I don't understand how I can insert the data to multiple tables. I also have a PK in Table_1 that is FK in Table_2 and Table_3 which I need to insert as well. I've been trying to figure this out for quiet a while and i really need some help.

If you need any additional information about structure or anything just ask and i will provide it not sure what you need to see :s

Best Regards Kevin! :)

EDIT:

So I have a form in AngularJS looking something like this:

form.html

<tr>
    <td>
        <input class="form-control" id="currency" ng-model="travelbill.Currency" ng-init="travelbill.Currency ='SEK'" type="text" />
    </td>
    <td>
        <input class="form-control" id="exchange_rate" ng-model="travelbill.Exchange_rate" type="number" />
    </td>
    <td>
        <input class="form-control" id="description" ng-model="travelbill.Description"/>
    </td>
    <td>
        <input class="form-control" id="sekinklmoms" ng-model="travelbill.SekInklMoms" type="number" />
    </td>
    <td>
        <input class="form-control" id="sekmoms" ng-model="travelbill.SekMoms" type="number" />
    </td>
    <td>
    </td>
</tr>

From there i call my Laravel with a controller:

Controller.php

class TravelbillController extends \BaseController {


  public function index() {
    return Response::json(Travelbill::all());
  }


  public function store() {
      $validator = Validator::make(
        array(
          'ResourceId' => Input::get('ResourceId')
        ),
        array(
          'ResourceId' => 'required'
        )
      );

      if($validator->fails()){
        App::abort(500, 'Validation Error!');
      } else {
        $travelbill = new Travelbill;
        $travelbill->ResourceId = Input::get('ResourceId');
        $travelbill->Destination = Input::get('Destination');
        $travelbill->Customer = Input::get('Customer.Name');
        $travelbill->StartDate = Input::get('StartDate');
        $travelbill->StartTime = Input::get('StartTime');
        $travelbill->EndDate = Input::get('EndDate');
        $travelbill->EndTime = Input::get('EndTime');
        $travelbill->Invoice = Input::get('Invoice');
        $travelbill->TravelCompensation = Input::get('TravelCompensation');
        $travelbill->save();


        $response = Response::json($travelbill);
      }

      return $response;
  }
}

From here i also want to insert the TravelbillId which is an increment value in the database into a table called Cost and Allowance where the FK is TravelbillId the relations i want is either one to one on both or one to many on Cost and One to One on Allowance .

I have some models also but I am not sure they are written correctly.

UserModel.php

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    protected $table = 'resource';
    protected $primaryKey = 'ResourceId';
    public $timestamps = false;

    public function supplier(){
        return $this->belongsTo('Supplier', 'SupplierId', 'SupplierId');
    }

    public function resourceData(){
        return $this->hasMany('OrderResourceData', 'ResourceId', 'ResourceId');
    }

    public function reportedTime(){
        return $this->hasMany('ReportedTime', 'ResourceId', 'ResourceId');
    }

    public function approvements(){
        return $this->hasMany('Approvement', 'ResourceId', 'ResourceId');
    }


}

TravelbillModel.php

<?php

  class Travelbill extends Eloquent {

    protected $table = 'travelbill';
    protected $primaryKey = 'TravelbillId';
    protected $fillable = array('ResourceId', 'Destination', 'StartDay', 'StartTime', 'EndDay', 'EndTime', 'Invoice', 'TravelCompensation');
    public $timestamps = true;

    public function travelbill() {
      return $this->belongsTo('User', 'ResourceId', 'ResourceId');
    }

    public function cost() {
      return $this->hasOne('Cost', 'TravelbillId', 'TravelbillId');
    }

    public function allowance() {
      return $this->hasOne('Allowance', 'TravelbillId', 'TravelbillId');
    }
  }

 ?>

CostModel.php

<?php

  class Cost extends Eloquent {

    protected $table = 'cost';
    protected $primaryKey = 'CostId';
    protected $fillable = array('TravelbillId', 'SekInklMoms');
    public $timestamps = false;

    public function cost() {
      return $this->belongsTo('Travelbill', 'TravelbillId', 'TravelbillId');
    }
  }


 ?>

It looks like you've largely done your models correctly, although without the database schema it's hard to say 100%. Basically, what you need to do is save and associate the set of records, first with the Travelbill , then the associated Cost and Allowance .

$travelBill = new Travelbill();
$travelBill->ResourceId = Input::get('ResourceId');
...
$travelBill->save(); // This should populate the TravelbillId primary key

$cost = new Cost();
$cost->SekInklMoms = ...; // The value of SekInklMoms

// Save the cost to DB *and* associate the models
$travelBill->cost()->save($cost);

// The JSON will contain travelBill *and* cost due to the association above
return Response::json($travelbill);

This should get you across the saving issue. The important thing to understand here is that you have to save the primary model first in order to save anything relying on its existence (ie associating the foreign keys with the primary). Keep in mind that could also do:

$travelBill->save();
$cost = new Cost();
$cost->SekInklMoms = ...;
$cost->TravelbillId = $travellBill->TravelbillId;
$cost->save();

The different here is that you are associating the two in the database only, and not your models in this request. This means that your returned JSON will only have the TravelBill in it.

Get comfortable with either approach first, then you may want to look at wrapping the whole set of model saving in a database transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM