我正在使用Laravel(来自CodeIgniter),并且我正在努力获得一个包含外键的表。
我有两张桌子:People
&Friends
我的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"}}
)
它只是没有插入到我的Friend
表中。我没有犯任何错误,所以我不确定我做错了什么。
编辑
以下是我为创建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();
});
编辑2
逐行扫描后,我在我的网络选项卡中看到了这一点:
Base table or view not found: 1146 Table 'myapplication.friend' doesn't exist
这告诉我在某个地方有拼写问题。系统正在查找应该是friends
的friend
。
编辑3
以下是我的朋友模型:
朋友
namespace App;
use Illuminate'Database'Eloquent'Model;
class Friend extends Model
{
//
}
protected $table = 'friends';
你的命名似乎是正确的,我不知道为什么它不起作用。