今回作成するモデル
Modelの書き方
(親側)User.php
<?php
namespace App\Models;
use App\Models\Profile;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
use HasFactory;
protected $fillable = [
"id",
"username",
"email",
"password"
];
public function profile(){
return $this->hasOne(Profile::class);
}
}
(子側)Profile.php
<?php
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model {
use HasFactory;
protected $fillable = [
"user_id",
"name",
"description",
];
public function user(){
return $this->belongsTo(User::class);
}
}
Migrationファイルの書き方
example.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create("users", function(Blueprint $table) {
$table -> bigIncrements('id');
$table -> string("username");
$table -> string("email");
$table -> string("password");//平文保存は危険なので絶対しない(これは例だから無視)
$table -> timestamps();
});
Schema::create("profile", function(Blueprint $table){
$table -> bigIncrements("id");
$table -> string("name");
$table -> string("description");
$table -> foreignId("user_id")->constrained("users")
$table -> timestamps();
}
}
}
追加
example.php
$user = User::create([
"username" => $username,//固有のユーザーネーム
"email" => $email,//メールアドレス
"password" => bcrypt($password)//パスワードをbcrypt()を使ってハッシュ化
]);
$profile = Profile::create([
"name" => $name,//文字列型の変数(名前が格納)
"description" => $description, //文字列型の変数(自己紹介が格納)
"user_id" => $user->id,
"user" => $user
])
取得
(親から子)example.php
$user = User::find(1)->with("profile"//Modelで指定したメソッド名);
$profile = $user->profile;//Modelで指定したメソッド名
(子から親)example.php
$profile = Profile::where("name", $name)->find();
$user = $profile->user;
注意
- where/getを使うと戻り値はCollection型になるのでforearchで1個づつ取り出してリレーションを参照しなければならない。