(laravel 文档阅读记录)
model
model casting
给一个模型的属性 指定类型,方便后续模型操作 1
relationship
Database tables are often related to one another. For example, a blog post may have many comments or an order could be related to the user who placed it.
1
relationship one-to-many relationship
a blog post has many comments
a comment belongs to a post
在 comments table 里有 post_id 栏位
1
relationship – 通过 belongsTo relationship
父模型更新子模型
在 a model 的视角,
通过 belongsTo relationship, a model “找到” 自己的子模型(实际上找到的是 $post->comments() 这个 relationship)并通过它追加一个属于自己的子模型(构成了新一个 belongsTo relationship, 保存在隐形的联表里? 因为一对多关系不需要显式的联表)。
1
use AppModelsComment;
use AppModelsPost;
$comment = new Comment(['message' => 'A new comment.']);
$post = Post::find(1);
$post->comments()->save($comment);
The save method will automatically add the appropriate post_id value to the new Comment model 1. 至此 comment model 处理完毕了,存储在 comments table 的时候 post_id 栏位有值 —— 否则 post_id 栏位 缺值,这是不对的。
子模型自我更新
在 a child model 的视角,
通过 belongsTo relationship, a child model 关联到 a new parent model
// user belongs to an account
use AppModelsAccount;
$user->account()->associate(Account::find(10));
$user->save();
// 这个叫做 to assign a child model to a new parent model, you may use the `associate` method. In this example, the User model defines a belongsTo relationship to the Account model. This `associate` method will set the foreign key on the child model.
// (对此 user, 更新了 users table 里的它的 account_id 栏位)
// a new parent model 是 account
// comment belongs to a post
use AppModelsPost;
$comment->post()->associate(Post::find(10));
$comment->save();
// a new parent model 是 post
// (对此 comment, 更新了 comments table 里的它的 post_id 栏位)