laravel入门-mysql一对多
1. 创建user和Job的model
1 php artisan make:migration order -m 2 3 php artisan make:migration user -m
2. 修改表结构Migration
1 cat create_user_table.php 2 3 public function up() 4 { 5 Schema::create('users', function (Blueprint $table) { 6 $table->increments('id'); 7 $table->string("username",50); 8 $table->string("age",3); 9 $table->string("email",50); 10 $table->timestamps(); 11 }); 12 } 13 14 cat create_order_table.php 15 16 Schema::create('orders', function (Blueprint $table) { 17 $table->increments('id'); 18 $table->unsignedInteger("user_id"); 19 $table->string("name",50); 20 $table->string("describe",5000); 21 $table->foreign("user_id") 22 ->references("id")->on("users") 23 ->onDelete("cascade"); 24 $table->timestamps(); 25 });
3. models 定义
1 cat User.php 2 3 <?php 4 5 namespace App; 6 7 use Illuminate\Database\Eloquent\Model; 8 9 10 class User extends Model 11 { 12 //要显示哪些列 13 protected $fillable = [ 14 'username','age','email' 15 ]; 16 17 18 function userTo() 19 { 20 return $this->hasMany('App\Order'); 21 } 22 23 } 24 25 26 // 里面定义了user 和 order的一对多的关系
4. 控制器
1 cat WeclomeController.php 2 3 $u = User::find(1); 4 return response($u->userTo); 5 6 7 /* 8 跨域解决 9 $response = response('') 10 ->header('Access-Control-Allow-Origin', '*') 11 ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json') 12 ->header('Access-Control-Allow-Methods', 'GET, POST') 13 ->header('Access-Control-Allow-Credentials', 'false'); 14 15 */
5. 常用的sql命令
3.1 删除索引 alter table `job` drop index job_user_id_foreign ; 3.2 增加索引 create unique index u_job_index on job(user_id) ; create index u_job_index on job(user_id) ; 3.3 增加外键 alter table `job` add constraint `job_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade ; 3.4 删除外键 alter table `job` drop foreign key job_user_id_foreign ;
知人难,相知相惜更难