//檔案:database/migrations/日期_編號_create_posts_table.php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned(); //正數
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
//下指令
php artisan migrate:refresh
資料庫的posts資料表將會增加user_id這個欄位
//檔案:APP/user.php
public function post(){
return $this->hasOne('App\Post','user_id');
//user_id其實是預設值
}
//檔案:routes/web.php
use App\User;
Route::get('user/{id}/post', function($id) {
return User::find($id)->post;
});
瀏覽器輸入:public/user/1/post
出現他那篇文章的文章物件
(post後面加->title,會出現標題,加->content,會出現內容)
//檔案:routes/web.php
use App\User;
use App\Post;
Route::get('post/{id}/user', function($id) {
return Post::find($id)->user->name;
});
//檔案:app/post.php
public function user(){
return $this->belongsTo('App\User');
}
瀏覽器輸入:public/post/1/user
出現編號1的文章的作者
//檔案:routes/web.php
Route::get('/posts', function() {
$user = User::find(1); //先確定有User這個model被use
foreach ($user->posts as $post) {
echo $post->title . "<br>";
}
});
//檔案:APP/user.php
public function posts(){
return $this->hasMany('App\Post');
}
瀏覽器輸入:public/posts
出現編號1會員的所有文章title
//下指令
php artisan make:model Role -m
//-m代表說會同時做migration
//下指令
php artisan make:migration create_users_roles_table --create=role_user
//新的名稱要放前面
//檔案:database/migrations/日期_編號_create_roles_table.php
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
//檔案:database/migrations/日期_編號_create_users_roles_table.php
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('role_id');
$table->timestamps();
});
}
//下指令
php artisan migrate
沒有留言:
張貼留言