モデルの基本的な使用
class User extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'password'];
}
// 使用例
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
PHPEloquentリレーションシップ
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
// 使用例
$post = Post::find(1);
$user = $post->user;
$comments = $post->comments;
PHPクエリビルダの活用
$users = User::where('active', 1)
->where('age', '>', 18)
->orderBy('name')
->limit(10)
->get();
PHPマイグレーションの作成と実行
database/migrations/xxxx_xx_xx_create_posts_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->foreignId('user_id')->constrained();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
PHPシーダーとファクトリの利用
database/seeders/UserSeeder.php
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
public function run()
{
\App\Models\User::factory(10)->create();
}
}
PHPdatabase/factories/UserFactory.php
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => bcrypt('password'),
];
}
}
PHPスコープとミューテータ
class User extends Model
{
// ローカルスコープ
public function scopeActive($query)
{
return $query->where('active', 1);
}
// グローバルスコープ
protected static function booted()
{
static::addGlobalScope('ancient', function (Builder $builder) {
$builder->where('created_at', '<', now()->subYears(2));
});
}
// ミューテータ
public function setNameAttribute($value)
{
$this->attributes['name'] = ucfirst($value);
}
}
// スコープの使用
$activeUsers = User::active()->get();
// ミューテータの使用
$user->name = 'john'; // 'John'として保存される
PHPテーブル内の全レコード取得
User::all();
PHPレコード存在確認
単一レコードの存在確認
User::where('id', 1)->count() > 0;
User::where('id', 1)->exists();
PHP複数レコードの存在確認
User::where('age', 20)->count() > 0;
User::where('age', 20)->get()->isEmpty();
PHP
コメント