在控制器中使用foreach时出现语法错误

时间:2019-03-28 06:17:06

标签: laravel laravel-5

这是我的控制器,在控制器中使用foreach时出现语法错误

namespace App\Http\Controllers;

use DB;

class course_controller extends Controller {

    public function show_details() {
        $prospects = DB::table('prospect')->get();

        foreach ($prospects as $prospect) {
            DB::table('course_prospect')->insert(['prospect_id' => 
$prospect->id, 'course_id' => $prospect->course_intrested])
        };

    }

}

6 个答案:

答案 0 :(得分:1)

您需要在插入方法后添加分号。

namespace App\Http\Controllers;

use DB;

class course_controller extends Controller {

    public function show_details() {
        $prospects = DB::table('prospect')->get();

        foreach ($prospects as $prospect) {
            DB::table('course_prospect')->insert(['prospect_id' => 
$prospect->id, 'course_id' => $prospect->course_intrested]);   // add semicolon here
        }   // don't need semi-colon here

    }

}

答案 1 :(得分:1)

public function show_details() {
    $prospects = DB::table('prospect')->get();

    foreach ($prospects as $prospect) {
        DB::table('course_prospect')->insert(['prospect_id' =>
            $prospect->id, 'course_id' => $prospect->course_intrested]); //Add semicolon here
    }
}

答案 2 :(得分:0)

您放错了分号,请在此处检查:

foreach ($prospects as $prospect) {
            DB::table('course_prospect')->insert(['prospect_id' => 
$prospect->id, 'course_id' => $prospect->course_intrested])
        }; <-- this one

将其更改为:

foreach ($prospects as $prospect) {
            DB::table('course_prospect')->insert(['prospect_id' => 
$prospect->id, 'course_id' => $prospect->course_intrested]);
        }

在每次迭代中触发插入查询,而是创建一个数组并将其保存在一个查询中并不是一个好主意。

答案 3 :(得分:0)

foreach ($prospects as $prospect) {
        DB::table('course_prospect')->insert(array('prospect_id' => $prospect->id, 'course_id' => $prospect->course_intrested));
    }

答案 4 :(得分:0)

您的;查询中缺少分号(insert):

foreach ($prospects as $prospect){  
   DB::table('course_prospect')->insert([  
      'prospect_id' => $prospect->id,
      'course_id'   => $prospect->course_intrested 
   ]); //You missed the semicolon here
} //remove semicolon from here

insert method的用于将记录插入数据库的语法

foreach的语法:

foreach($prospects as $prospect){

}   

答案 5 :(得分:0)

您放错了;并导致了问题

并且我也建议您使用关联的模型,而不要像下面这样使用DB

use App/Prospect;
use App/CourseProspect;

class course_controller extends Controller {

    public function show_details() {
        $prospects = Prospect::all();

        foreach ($prospects as $prospect) {
            CourseProspect::create([['prospect_id' => 
$prospect->id, 'course_id' => $prospect->course_intrested]]);
        };
    }
}