[英]How can I insert data into different tables using the same controller?
I am using Laravel (coming from CodeIgniter) and I am struggling on getting a table that contains a foreign key populated. 我正在使用Laravel(来自CodeIgniter),我正在努力获得一个包含填充外键的表。
I have two tables: People
& Friends
我有两张桌子:
People
Friends
My People
table has fields like "First Name", "Last Name" etc. 我的
People
表中包含“名字”,“姓氏”等字段。
At the bottom of my form, I can add a friend. 在我的表单底部,我可以添加一个朋友。 Each friend can have a "First Name", "Last Name" etc. I can add as many friends as I like.
每个朋友都可以拥有“名字”,“姓氏”等。我可以添加尽可能多的朋友。
I am successfully populating my People
table, then loop through my friends fields to populate my Friends
table. 我成功填充了我的
People
表,然后遍历我的朋友字段以填充我的Friends
表。
MyController.php 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();
}
}
If I log out $friend, I am seeing everything correctly. 如果我退出$ friend,我看到的一切都正确。 For example,
例如,
[attributes:protected] => Array
(
[person_id] => 4
[friend_data] => {"friend":{"firstName":"Tyler","lastName":"Durden","address":"12345 Street","city":"My City","state":"CA","zip":"12345"}}
)
It's just not getting inserted into my Friend
table. 它只是没有插入我的
Friend
表。 I'm not getting any errors so I'm not sure what I'm doing wrong. 我没有收到任何错误,所以我不确定我做错了什么。
EDIT 编辑
Here is what my migration looks like to create my Friends
table. 这是我的迁移看起来像创建我的
Friends
表的内容。
...
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();
});
EDIT 2 编辑2
After going line by line, I am seeing this in my network tab: 逐行后,我在网络标签中看到了这个:
Base table or view not found: 1146 Table 'myapplication.friend' doesn't exist
So that tells me I have a spelling problem somewhere. 所以这告诉我在某处有拼写问题。 The system is looking for
friend
when it should be friends
. 当它应该是
friend
时,系统正在寻找friends
。
EDIT 3 编辑3
Here is what my friend model looks like: 这是我朋友模特的样子:
Friend 朋友
namespace App;
use Illuminate\Database\Eloquent\Model;
class Friend extends Model
{
//
}
Laravel uses lots of conventions. Laravel使用了很多惯例。 One of them is that the model's name should be the singular of the table's name.
其中之一是模型的名称应该是表名的单数。 For your friends table, the model should be Friend.
对于你的朋友表,该模型应该是朋友。 In case you prefer to use your own naming, you can set the table in the model like this:
如果您更喜欢使用自己的命名,可以在模型中设置表格,如下所示:
protected $table = 'friends';
Your naming seems correct, I'm not sure why it isn't working. 你的命名似乎是正确的,我不确定它为什么不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.