php 保存数据到不同表,php – 如何使用同一个控制器将数据插入到不同的表中?...

我正在使用Laravel(来自CodeIgniter),我正在努力获得一个包含填充外键的表.

我有两张桌子:People&友

我的人员表中包含“名字”,“姓氏”等字段.

在我的表单底部,我可以添加一个朋友.每个朋友都可以拥有“名字”,“姓氏”等.我可以添加尽可能多的朋友.

我成功填充了我的People表,然后遍历我的朋友字段以填充我的Friends表.

MyController.php

if ($person->save()) { // Save the primary record.

// check if there are any friends to save.

$friendsArray = array_filter($input['friend']);

if (empty($friendsArray)) {

// No friends to insert.

} else {

$friend = new Friend();

$friend->person_id = $person->id;

$friend->friend_data = json_encode(array('friend' => $input['friend']));

$friend->save();

}

}

如果我退出$friend,我看到的一切都正确.例如,

[attributes:protected] => Array

(

[person_id] => 4

[friend_data] => {"friend":{"firstName":"Tyler","lastName":"Durden","address":"12345 Street","city":"My City","state":"CA","zip":"12345"}}

)

它只是没有插入我的朋友表.我没有收到任何错误,所以我不确定我做错了什么.

编辑

这是我的迁移看起来像创建我的朋友表的内容.

...

Schema::create('friends', function (Blueprint $table) {

$table->increments('id');

$table->integer('person_id')->unsigned();

$table->foreign('person_id')->references('id')->on('people');

$table->text('friend_data');

$table->timestamps();

});

编辑2

逐行后,我在网络标签中看到了这个:

Base table or view not found: 1146 Table 'myapplication.friend' doesn't exist

所以这告诉我在某处有拼写问题.当它应该是朋友时,系统正在寻找朋友.

编辑3

这是我朋友模特的样子:

朋友

namespace App;

use Illuminate\Database\Eloquent\Model;

class Friend extends Model

{

//

}

最佳答案 Laravel使用了很多惯例.其中之一是模型的名称应该是表名的单数.对于你的朋友表,该模型应该是朋友.如果您更喜欢使用自己的命名,可以在模型中设置表格,如下所示:

protected $table = 'friends';

你的命名似乎是正确的,我不确定它为什么不起作用.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值