Eloquent は、SQLを自分で書き、インターフェースに 対応づけます。実装クラスは書きません。 Ray.MediaQuery インターフェースとSQL // src/Query/PostItemInterface.php interface PostItemInterface { #[DbQuery('post_item', type: 'row')] public function __invoke(int $id): array; } -- var/sql/post_item.sql SELECT id, title, body FROM post WHERE id = :id; ユーザーのためのBEAR.Sunday入門 39 · Laravel
factory: UserFactory::class)] public function __invoke(int $id): User; } -- user_item.sql SELECT name, birthdate FROM user WHERE id = :id; の birthdate が、factoryで age を持つドメインオブジェクトに なります。 DB UserFactory final class UserFactory { public function __construct( private ClockInterface $clock, ) {} public function factory( string $name, string $birthdate, ): User { return new User($name, new DateTimeImmutable($birthdate), $this->clock->now()); } } ユーザーのためのBEAR.Sunday入門 42 · Laravel
function __invoke(): array; } interface PostAddInterface { #[DbQuery('post_add')] public function add( string $title, string $body ): InsertedRow; } var/sql -- post_list.sql SELECT id, title FROM post ORDER BY id DESC; -- post_add.sql INSERT INTO post (title, body) VALUES (:title, :body); ユーザーのためのBEAR.Sunday入門 44 · Laravel
{ protected function casts(): array { return ['author_id' => AuthorIdCast::class]; } } 変換の規則は、モデルが持ちます。 : の直前で値になる BEAR.Sunday SQL final class AuthorId implements ToScalarInterface { public function __construct(private int $id) {} public function toScalar(): int { return $this->id; } } #[DbQuery('post_add')] public function add(AuthorId $authorId): void; 変換の規則は、値オブジェクト自身が持ちます。 ユーザーのためのBEAR.Sunday入門 49 · Laravel
{ Post::create($request->validated()); } 検証済みの値は、配列で渡ります。 :入力オブジェクトを渡す BEAR.Sunday final class PostInput { public function __construct( #[Input] public readonly string $title, #[Input] public readonly string $body, ) {} } #[DbQuery('post_add')] public function add(PostInput $input): void; 検証済みの値は、型の付いたオブジェクトのまま渡ります。 ユーザーのためのBEAR.Sunday入門 50 · Laravel
2.103 SELECT * FROM `posts` WHERE `id` = 1 LIMIT 1 テーブル名からモデルを推し、組み立てたコードを 探します。発行元を残すには、laravel-sql-commenter などの パッケージを入れます。 # Query_time: 2.103 -- post_item.sql SELECT * FROM post WHERE id = 1 がそのままファイル名なので、開いて直せます。 ID ユーザーのためのBEAR.Sunday入門 53 · Laravel
Model { protected $fillable = ['title', 'body']; } public function comments() { return $this->hasMany(Comment::class); } // 属性はテーブル定義から実行時に現れる :フレームワークが合わせる BEAR.Sunday final class Post { public function __construct( public readonly int $id, public readonly string $title, public readonly string $body, ) { if ($title === '') { throw new EmptyTitle(); } } } ユーザーのためのBEAR.Sunday入門 64 · Laravel