Laravel从每个到数组如何?

时间:2018-06-28 05:07:23

标签: php laravel

这是使用dd $($ value)的Foreach循环get方法的结果,

问题:如何将其在控制器内部转换为数组并将其存储到数据库中

示例:[ Lead_id1 = Subjectid1,Lead_id2 = Subjectid1,Lead_id3 = Subjectid1 ] 如此等等。

注意: Lead_id和Subject_id都为 FK ,因为该值必须为整数Not String

控制器:

public function store(Request $request)
{
    $value=$request->all();
    $subjects = $value['Subject_id'] ?? [];
    $leads = $value['Lead_id'] ?? [];
    $data = [];
     foreach ($subjects as $subject) {
     $data[] = array_combine($leads, array_fill(0, count($leads), $subject));

    $scores=new Score;
    $scores->Subject_id=$request->input('Subject_id');
    $scores->Lead_id=$request->input('Lead_id');
   dd($scores);
    $scores->save();
}

这是结果 enter image description here enter image description here

得分模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Score extends Model
{
    protected $guarded = [
        'id',
        'Year_id',
        'Term_id',
        'Level_id',
        'Classes_id',
        'Subject_id',
        'Lead_id',
    ]; 
}

4 个答案:

答案 0 :(得分:2)

您说Lead_id and Subject_id都是外键,那么您只需在laravel中使用ManyToMany关系并相应地保存数据

  

主题模型

class Subject extends Model{
   public function leads(){
     return $this->belongsToMany(Lead::class, 'scores', 'Subject_id', 'Lead_id');
   }
}
  

领导模型

class Lead extends Model{
   public function subjects(){
     return $this->belongsToMany(Subject::class, 'scores', 'Lead_id', 'Subject_id');
   }  
}

问题:如何将其在控制器内部转换为数组并将其存储到数据库中

foreach($data['Subject_id'] as $subjectId){
    $subject = Subject::find($subjectId);
    $leadids = $data['Lead_id'];
    $subject->leads()->attach($leadids);
}

有关详细信息,请检查此https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

答案 1 :(得分:0)

您可以尝试-

$temp = [];
$subject = !empty($value['Subject_id'][0]) ? $value['Subject_id'][0] : null; // extract the subject id
// Loop through lead ids
foreach($value['Lead_id'] as $lead) {
    $temp[$lead] = $subject; // store subject id fro lead ids
}

答案 2 :(得分:0)

您可以尝试以下操作:

public function store(Request $request)
{
    $value=$request->all();
    $subjects = $value['Subject_id'] ?? [];
    $leads = $value['Lead_id'] ?? [];
    $data = [];

    foreach ($subjects as $subject) {
        $data[] = array_combine($leads, array_fill(0, count($leads), $subject));
    }

    foreach ($data as $load => $subject) {
        $scores = new Score;
        $scores->Subject_id = $subject;
        $scores->Lead_id = $load;
        $scores->save();
        dd($scores);
    }  
}

答案 3 :(得分:-2)

首先将数组转换为json字符串

json_encode($array);

将其存储到数据库之前