首页 > 后端开发 > php教程 > laravel5一对多的create问题

laravel5一对多的create问题

WBOY
发布: 2016-06-06 20:23:23
原创
1714 人浏览过

<code>array:7 [▼
  "_token" => "Y9szFJQYRcmHpyBB1McOE9tbUoZmshmJHzfV1hMG"
  "title" => "1"
  "image" => "2"
  "itemimages" => array:2 [▼
    0 => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_60053.png"
    ]
    1 => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_32261.png"
    ]
  ]
  "category_id" => "4"
  "content" => "3"
  "text" => "3"
]</code>
登录后复制
登录后复制

一个表单传递过来一个商品的信息,并且这个商品

<code>        $data=$request->all();
        $data['text']=mb_substr($data['content'],0,64);
        $save=Item::create($data);</code>
登录后复制
登录后复制

商品创建成功,然后需要往图片库里加图片$data['itemimages'],

<code>$save->itemimages()->save($data['itemimages']);//报错
$save->itemimages()->saveMany($data['itemimages']);//报错
$save->itemimages()->create($data['itemimages']);//item_id有值,image为空</code>
登录后复制
登录后复制

后来尝试格式换一下

<code>"itemimages" => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_60053.png"
  ]

$save->itemimages()->create($data['itemimages']);//成功</code>
登录后复制
登录后复制

那么多张图片怎么办

Item已经定义

<code>public function itemimages(){
    return $this->hasMany("App\Itemimage");
}</code>
登录后复制
登录后复制

回复内容:

<code>array:7 [▼
  "_token" => "Y9szFJQYRcmHpyBB1McOE9tbUoZmshmJHzfV1hMG"
  "title" => "1"
  "image" => "2"
  "itemimages" => array:2 [▼
    0 => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_60053.png"
    ]
    1 => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_32261.png"
    ]
  ]
  "category_id" => "4"
  "content" => "3"
  "text" => "3"
]</code>
登录后复制
登录后复制

一个表单传递过来一个商品的信息,并且这个商品

<code>        $data=$request->all();
        $data['text']=mb_substr($data['content'],0,64);
        $save=Item::create($data);</code>
登录后复制
登录后复制

商品创建成功,然后需要往图片库里加图片$data['itemimages'],

<code>$save->itemimages()->save($data['itemimages']);//报错
$save->itemimages()->saveMany($data['itemimages']);//报错
$save->itemimages()->create($data['itemimages']);//item_id有值,image为空</code>
登录后复制
登录后复制

后来尝试格式换一下

<code>"itemimages" => array:1 [▼
      "image" => "/editor/php/../attached/image/20151203/20151203071049_60053.png"
  ]

$save->itemimages()->create($data['itemimages']);//成功</code>
登录后复制
登录后复制

那么多张图片怎么办

Item已经定义

<code>public function itemimages(){
    return $this->hasMany("App\Itemimage");
}</code>
登录后复制
登录后复制

<code>$itemimages=[];
foreach($data['itemimages'] as $v){
    $itemimages[]=new App\Itemimage(['image' => $v['image']),
}

$save->itemimages()->saveMany($itemimages);</code>
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板