我有三个相互关联的表,引发多态一对多关系
表格
users
id - integer
name - string
office
id - integer
name - string
phones
id - integer
name - string
phones_id - integer
phones_type - string
我想在与特定用户相关的phones
表中添加电话号码
user.php
public function phones()
{
return $this->morphMany('App\Phone', 'phones');
}
Phone.php
public function phones()
{
return $this->morphTo();
}
Create.blade.php
<form action="{{route('dashboard.users.store')}}" method="post">
<div class="input-group control-group after-add-more">
<input type="text" name="phone[]" class="form-control">
<div class="input-group-btn">
<button class="add-more" type="button">Add</button>
</div>
</div>
<button type="submit">save</button>
</form>
<!-- Copy Fields -->
<div class="copy" hidden>
<div class="control-group input-group">
<input type="text" name="phone[]" class="form-control">
<div class="input-group-btn">
<button class="remove" type="button">Remove</button>
</div>
</div>
</div>
JavaScript
<script>
$(document).ready(function() {
$(".add-more").click(function(){
var html = $(".copy").html();
$(".after-add-more").after(html);
});
$("body").on("click",".remove",function(){
$(this).parents(".control-group").remove();
});
</script>
我正在尝试将记录存储到电话中,并使用UserController.php
if ($request->phone) {
$user->phones()->saveMany($request->phone);
}
但这给我一个错误
参数1传递给 Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()必须是 Illuminate \ Database \ Eloquent \ Model的实例,给定的字符串,称为 在 C:\ Server \ data \ htdocs \ justice_way \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany.php 在第264行
dd($request)
给了我
"phone" => array:2 [▼
0 => "+1 (776) 209-9366"
1 => "+1 (444) 579-3232"
]
当我尝试
if ($request->phone) {
$phone = new Phone;
$phone->name = $request->phone;
$user->phones()->save($phone);
}
出现错误
传递给Illuminate \ Database \ Grammar :: parameterize()的参数1必须 属于int类型的数组,称为 C:\ Server \ data \ htdocs \ justice_way \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Query \ Grammars \ Grammar.php 在871行上
答案 0 :(得分:0)
最后我明白了
if ($request->phone) {
foreach ($request->phone as $key => $value) {
$phone = new Phone;
$phone->name = $value;
$nyaba->phones()->save($phone);
}
}