2017-09-23 132 views
1
class PostController extends Controller{ 
    public $grupID = 1; 
    public function store(Request $request) 
    { 
     $post = new Post(); 
     $post->GroupID = 'POST-' . $this->grupID; 
     $post->save(); 
     return response()->json($post); 
     $this->grupID++; 
    } 
} 

数据库StructurLaravel存储数据自动递增

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('PostTypeID'); 
     $table->string('GroupID', 100)->nullable(); 
     $table->timestamps(); 
    }); 
} 

我想使组ID自动递增,但它总是返回 'POST-1'。

+0

分享你的数据库/表是怎么样子? – C2486

+0

对不起,我对错误的人回复评论...我已经尝试了你的代码..但是groupID不会增加.. –

+0

为什么groupid是post增量?只有post id应该增加默认值。 ? – C2486

回答

0
class PostController extends Controller{ 
    public function store(Request $request) 
    { 
     $lastValue = DB::table('posts')->orderBy('GroupID', 'desc')->first(); 
     if(count($lastValue) < 1){ 
     $post->GroupID = 'POST-' . 1;  
     }else{ 
     $last = substr($lastValue->GroupID, strrpos($lastValue->GroupID, '0') + 1); 
     $post->GroupID = 'POST-' . $last + 1; 
     } 
     $gid = $post->GroupID; 
     $post->save(); 
     return response()->json($post); 
    } 
} 
0

当您使用return语句时,执行停止,所以您的增量永远不会发生。把return语句放在最后。

+0

我已经把它放在最后,但增量不起作用 –

+0

根据你的函数,变量每次运行时都会被重置为1。你是否每次运行都要计算它?您需要将值提交给数据库表。 – GoogleMac

1

在您的数据库迁移文件
$ table-> increment('grupID');

它会自动递增。

+0

他在找什么是一个自定义增量:)使用字符串“Post-”(和增量值)而不是默认值:) – emjr

2

试试这个,你需要在你的数据库,以获得最后的值,

class PostController extends Controller{ 
     public function store(Request $request) 
     { 
      $lastValue = DB::table('posts')->orderBy('GroupID', 'desc')->first(); 
      $post = new Post(); 
      $post->GroupID = 'POST-' . $lastValue->GroupID + 1 ; 
      $post->save(); 
      return response()->json($post); 
     } 
    } 

希望这有助于:)

+1

你说的是对的,但是你的代码是错误的。 '$ lastValue'对象不是任何整数值。还有,如果表中没有值,会发生什么?你有我的观点? – C2486

+0

我得到了这个错误“class stdClass的对象无法转换为int” –

+0

对不起,我忘了链接它。 @jamesriady答案更新:) – emjr