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.

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

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)