4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel4でinsert直後のidを自動取得したい件

4
Posted at

下記のようなテーブルがあるとする。

mysql> desc company_basic_info;
+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name          | varchar(255)     | NO   | UNI | NULL    |                |
| kana          | varchar(255)     | NO   | UNI | NULL    |                |
| tel           | varchar(40)      | NO   | UNI | NULL    |                |
| fax           | varchar(40)      | NO   | UNI | NULL    |                |
| address       | varchar(255)     | NO   | UNI | NULL    |                |
| url           | varchar(255)     | NO   | UNI | NULL    |                |
| establishment | date             | NO   |     | NULL    |                |
| capital       | int(11)          | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

名前や電話番号などの会社情報を入力するテーブル。
id は auto_increment なので、インサート時に自動的に振られる。
その id を取得したい場合は、

$id = DB::getPdo()->lastInsertId();

を使う。具体的には、下記のように実装する。

public function insert()
{

    $name          = Input::get('name');
    $kana          = Input::get('kana');
    $tel           = Input::get('tel');
    $fax           = Input::get('fax');
    $address       = Input::get('address');
    $url           = Input::get('url');
    $establishment = Input::get('establishment');
    $capital       = Input::get('capital');

    $result =
    DB::table('company_basic_info')->insert([
            'name'         => $name,
            'kana'         => $kana,
            'tel'          => $tel,
            'fax'          => $fax,
            'address'      => $address,
            'url'          => $url,
            'establishment'=> $establishment,
            'capital'      => $capital
    ]);

    if($result){
            $id = DB::getPdo()->lastInsertId();
            echo $id;
    }

    return 'hoge';

}

ここで、$result には、insert の結果が入る(idではない)。
insert が成功したら $result は 1 になる。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?