dpkt17803 2018-09-05 11:10
浏览 63
已采纳

Laravel 4.2和AngularJS将数据插入到多个表中,其中Table_1中的PK是表2和表_3中的FK

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 theTravelbillId 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');
    }
  }


 ?>
  • 写回答

1条回答 默认 最新

  • doufunuo4787 2018-09-05 19:48
    关注

    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 (i.e. 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度